我有一个类似于这样的XML文件:
<booking-info-list>
<booking-info>
<index>1</index>
<pricing-info-index>1</pricing-info-index>
<booking-type>W</booking-class>
<cabin-type>E</cabin-type>
<ticket-type>E</ticket-type>
<booking-status>P</booking-status>
</booking-info>
<booking-info>
<index>2</index>
<pricing-info-index>1</pricing-info-index>
<booking-type>W</booking-class>
<cabin-type>E</cabin-type>
<ticket-type>E</ticket-type>
<booking-status>P</booking-status>
</booking-info>
<booking-info>
<index>3</index>
<pricing-info-index>1</pricing-info-index>
<booking-type>W</booking-class>
<cabin-type>E</cabin-type>
<ticket-type>E</ticket-type>
<booking-status>P</booking-status>
</booking-info>
</booking-info-list>
是否有一种简单的方法可以替换/删除所有代码中的-
(连字符)?
答案 0 :(得分:1)
连字符不是XML节点名称中的特殊字符。这是SimpleXML中的一个问题,因为它是PHP中的运算符。这里不需要更改它们并可能破坏XML。
您可以使用变量变量语法来访问元素。
$element = simplexml_load_string($xml);
foreach($element->{'booking-info'} as $element) {
var_dump($element);
}
如果你正在使用Xpath,那不是问题:
$element = simplexml_load_string($xml);
foreach ($element->xpath('//booking-info') as $element) {
var_dump($element);
}
Xpath表达式是PHP的字符串。
或DOM:
$document = new DOMDocument();
$document->loadXml($xml);
foreach ($document->getElementsByTagName('booking-info') as $node) {
var_dump($node);
}
该名称是PHP的字符串。
或者带有XPath的DOM:
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('//booking-info') as $node) {
var_dump($node);
}
提示:XML中存在错误 - <booking-type>...</booking-class>
具有不同的开始和结束标记名称。