douhuang7263 2010-07-01 04:07 采纳率: 100%
浏览 32
已采纳

PHP DOM使用新行追加子项

My name Rithy.

I don't know how to add new line before appending a new node or element in the xml.

My php:

$dom = new DOMDocument();

$dom->formatOutput = true;

$dom->preserveWhiteSpace = true;

$dom->load($xml_file);

$body = $dom->getElementsByTagName('body')->item(0);

$newelement_seg = $dom->createElement('seg');

$data = $dom->createTextNode(" text 2 ");  

$newelement_seg->appendChild($data);

$body->appendChild($newelement_seg);

$dom->save($xml_file);

XML Before append a new child:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <seg>
        text 1
    </seg>
</body>
</xml>

XML after append a new child:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <seg>
        text 1
    </seg>
    <seg>
        text 2
    </seg>
</body>
</xml>

But I want:

<?xml version="1.0" encoding="UTF-8"?>
    <body>
        <seg>
            text 1
        </seg>
        <seg>
            text 2
        </seg>
    </body>
</xml>
<hr/>

Thanks in advance!

  • 写回答

3条回答 默认 最新

  • donglinli2027 2010-07-01 04:11
    关注

    What are you trying to accomplish?

    By setting preserveWhiteSpace to true (unnecessary; that's the default), you are telling libxml not to ignore text nodes that are composed only of white space. Yet, at the same time, you're trying to pretty format the XML file, which to be really pretty requires whitespace nodes.

    Then, even ignoring white space, you have to realize the whitespace inside the <seg> tags is significant; libxml will not remove those; if you force a line break after text 1, in the next line the </seg> closing tag must not be indented, otherwise the content of the text node inside the tag would differ.

    Your code gives me this:

    <?xml version="1.0" encoding="UTF-8"?>
    <body>
    <seg>
      text 1  
    </seg>
    <seg> text 2 </seg></body>
    

    Since you're telling libxml that whitespace is significant, it cannot put a line break after the second </seg>, otherwise it'd be creating another text node.

    If you say $dom->preserveWhiteSpace = false;:

    <?xml version="1.0" encoding="UTF-8"?>
    <body>
      <seg>
      text 1  
    </seg>
      <seg> text 2 </seg>
    </body>
    

    The tags are indented, but libxml still cannot do this:

    <?xml version="1.0" encoding="UTF-8"?>
    <body>
      <seg>
        text 1  
      </seg>
      <seg>
        text 2
      </seg>
    </body>
    

    because it would be changing the content of the text nodes inside <seg>.

    You might want to try tidy, though I'm not sure it'll do what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路