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条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题