开发者

How can I auto-indent XML nodes with XML::LibXML?

开发者 https://www.devze.com 2023-03-31 08:58 出处:网络
I\'m adding nodes to my XML document as part some in-house processing, but cannot get XML::LibXML to auto-indent the added nodes.

I'm adding nodes to my XML document as part some in-house processing, but cannot get XML::LibXML to auto-indent the added nodes.

I get output like the following:

Here's what I'm currently getting with $xml->toString( 1 ):

                                    <nested_nodes>
                                        <nested_node>
                                        <configuration>A</configuration>
                                        <model>45</model>
                                        <added_node>
        <ID>
            <type>D</type>
            <serial>3</serial>
            <kVal>3</kVal>
        </ID>
    </added_node>
</nested_node>
                                    </nested_nodes>

What I would like to have is pretty-printed output:

                            <nested_nodes>
                                <nested_node>
                                    <configuration>A</configuration>
                                    <model>45</model>
                                    <added_node>
                                        <ID>
                                            <type>D</type>
                                            <serial>3</serial>
                                            <kVal>3</kVal>
                                    开发者_开发百科    </ID>
                                    </added_node>
                                </nested_node>
                            </nested_nodes>

The optional $format parameter for the toString() method documented in XML::LibXML::Document doesn't seem to help.


I played a bit with settings and this seems to work:

use XML::LibXML;

my $doc = XML::LibXML->load_xml(string => <<END_XML, { no_blanks => 1 });
                                    <nested_nodes>
                                        <nested_node>
                                        <configuration>A</configuration>
                                        <model>45</model>
                                        <added_node>
        <ID>
            <type>D</type>
            <serial>3</serial>
            <kVal>3</kVal>
        </ID>
    </added_node>
</nested_node>
                                    </nested_nodes>
END_XML

print $doc->toString(1);

Result is this:

<?xml version="1.0"?>
<nested_nodes>
  <nested_node>
    <configuration>A</configuration>
    <model>45</model>
    <added_node>
      <ID>
        <type>D</type>
        <serial>3</serial>
        <kVal>3</kVal>
      </ID>
    </added_node>
  </nested_node>
</nested_nodes>


If you don't mind using another tool, I recommend XML::Tidy. It does one job, and it does it well.

0

精彩评论

暂无评论...
验证码 换一张
取 消