简体   繁体   English

在XML文档中有条件地插入文本节点

[英]Conditionally insert text node in XML document

The structure of my XML document is the following: 我的XML文档的结构如下:

<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>

...
<seg>
<source>source_text</source>
</seg>

</tr>

Note that the dest element is not always present. 请注意,dest元素并不总是存在。 I want to scan the file with PHP and insert a dest element (with some text) each time it's not present in a seg node. 我想用PHP扫描文件,并在seg节点中每次不存在时插入一个dest元素(带有一些文本)。

Any help would be very appreciated. 任何帮助将不胜感激。 Patrick 帕特里克

Try this, I tested this snippet, works for me: 试试这个,我测试了这个片段,对我有用:

$xml = '<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>
<seg>
<source>source_text</source>
</seg>
</tr>
';
$xmlObj = new SimpleXMLElement($xml);
foreach($xmlObj as $seg) {
    if(!$seg->dest) {
        $seg->dest = 'dest_text_inserted';
    }
}
echo $xmlObj->asXML();

It outputs what you need: 它输出您需要的内容:

<?xml version="1.0"?>
<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>
<seg>
<source>source_text</source>
<dest>dest_text_inserted</dest></seg>
</tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM