Parsing XML with line breaks / newline characters

2019-08-03 04:03发布

问题:

I'm trying to parse a series of XML files with Perl's XML::LibXML module.

<log date="2012-08-07 18:05:44.0" level="unit" label="2G-or-3G-server" name="unitnote" value="# Firmware level after downgrade
#
-&amp;gt; show /HOST

 /HOST
    Targets:
        bootmode
        diag
        domain ...."

Where some of the values contain output from the execution of scripts. When I try to parse these values, I end up with something like the following:

my $value  = $log->findvalue('@value');
print "value: $value\n";

Output:

# Firmware level after downgrade    #   -&amp;gt; show /HOST  /HOST  Targets:      bootmode        diag        domain ....

I can't seem to find any way to have LibXML respect newlines. Any idea?

回答1:

The XML 1.0 Specification says that any whitespace characters in attribute values (space, CR, LF, tab) must be converted to a space before processing

Unfortunately any properly-working XML processor will give you the same problem

This is very odd XML. Where did it come from? The value attribute should really be presented as PCDATA so that it can be processed properly. Is there any way you can change the data you are getting?

If there is any way you could preprocess the data so that your newlines are replaced with character references &#xA; then they will be translated to LF characters when the data is processed. This really should be done by whatever is generating the XML



回答2:

The Attribute-Value Normalization section of the XML spec requires the behaviour exhibited by XML::LibXML.

For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value.

There is no documented option to change this behaviour.

If the attribute value is suppose to contain a newline, &#x0A; or similar has to be used instead of an actual newline.



标签: xml perl libxml2