Parsing XML with line breaks / newline characters

2019-08-03 03:41发布

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?

标签: xml perl libxml2
2条回答
等我变得足够好
2楼-- · 2019-08-03 04:05

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

查看更多
欢心
3楼-- · 2019-08-03 04:28

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.

查看更多
登录 后发表回答