我在PHP中使用simplexml_load_file函数来遍历xml文件。
我被困在某种意义上,我正试图访问一个特定的meta对象的值,但我不知道该怎么做。
此代码有效,但并非每个xml文件都相同,所以我希望能够通过某种方式获取主题的值。
<?php
$file = simplexml_load_file('test.xml');
$subject = $file->head->meta[1][content];
print($subject);
?>
所以基本上我可以使用$file->head->meta[1][content]
直接遍历$ subject,但就像我说的那样,这并不总是有效。
在Python中,我使用subject = self.element.find(".//meta[@name='subject']/ @content")
以下是我正在解析的一些xml的示例:
<?xml version="1.0" encoding="windows-1252"?>
<nitf>
<head>
<meta name="ProgramVersion" content="2.0"/>
<meta name="subject" content="XML test nonjump"/>
<meta name="Category" content="Business"/>
<meta name="Priority" content="Inside"/>
<meta name="Format" content="3cB"/>
<meta name="AuthorID" content="532944370"/>
<ads/>
<docdata>
<correction id-string="401"/>
<urgency ed-urg="7"/>
<date.release norm="2014-03-21T00:01:00-07:00"/>
<doc.copyright year="2014" holder="APWire"/>
<date.expire norm="2014-04-18T12:01:00-07:00"/>
<identified-content/>
</docdata>
</head>
<body>
<body.head>
<hedline>
<hl1 style="@Hed Benton">Test: British unemployment stays at 7.2 percent reinforcing BOE guidance message</hl1>
</hedline>
<byline>
<p style="@Byline">By Test User</p>
<p style="@Byline2">Bloomberg News</p>
</byline>
</body.head>
<body.content>
<block>
<p style="@Subhed 1 col" lede="true">Repeating to correct keyword</p>
<p style="@Body justified">LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.</p>
<p style="@Body justified">The jobless rate measured by International Labour Organization methods was 7.2 percent, the same as in the final quarter of 2013 the Office for National Statistics said in London Wednesday. That’s in line with the median forecast in a Bloomberg survey. Jobless claims - a narrower measure of unemployment, fell 34,600, more than economists had forecast, and wage growth accelerated.</p>
<p style="@Body justified">The figures hand ammunition to BOE Governor Mark Carney’s argument that officials should be in no hurry to increase borrowing costs. Rapid falls in unemployment last year forced the BOE to abandon the 7 percent threshold for considering a rate increase. Policy makers said last month they’re now focused on a broader range of measures of spare capacity.</p>
</block>
</body.content>
</body>
</nitf>
答案 0 :(得分:1)
你在python中起诉“Xpath”,它也可以在SimpleXML中使用。
$result = $element->xpath(".//meta[@name='subject']/ @content");
文档在这里:http://www.php.net/manual/en/simplexmlelement.xpath.php