我将以下XML代码段作为我使用最新OmniXML快照处理的更大XML文件的一部分:
<OrderRequestHeader>
<!-- snipped XML bits here -->
<ShipTo>
<Address addressID="">
<Name xml:lang="en">SOME COMPANY</Name>
<PostalAddress name="default">
<DeliverTo>John Doe</DeliverTo>
<Street>123 Any St</Street>
<City>Nowhere</City>
<State>AK</State>
<PostalCode>99999</PostalCode>
<Country isoCountryCode="US">United States</Country>
</PostalAddress>
<Email/>
<Phone>
<TelephoneNumber>
<CountryCode isoCountryCode=""/>
<AreaOrCityCode/>
<Number></Number>
</TelephoneNumber>
</Phone>
</Address>
</ShipTo>
<!-- more XML stuff follows -->
</OrderRequestHeader>
我目前有一个指向<ShipTo>
节点的变量,并且想要选择<Name>
节点的内容。我正在使用以下代码,但Node2
即将出现Nil
...
procedure ProcessXML;
var
Node1, Node2: IXMLNode;
begin
Node1 := FindNode(OrderHeader, 'ShipTo');
// the above is working. Node points to the <ShipTo> node
Node2 := SelectNode(Node1, 'Name');
// the above line doesn't work. Node2 is Nil
end;
为什么Node2
Nil
?根据{{1}}中的帮助,OmniXMLUtils.pas
将选择一个节点可能超过以下一个级别。肯定有一个SelectNode
节点。即使尝试通过<Name>
找到节点也会返回一个空列表。我是否以某种方式使用OmniXML?如果没有先选择XPathSelect(Node1, 'Name');
节点,是否可以到达<Name>
节点?
答案 0 :(得分:1)
SelectNode
可以正常工作,如果你在前面添加双斜杠字符:
var
FXMLDocument: IXMLDocument;
// Somewhere along the line
FXMLDocument := CreateXMLDocument
XMLLoadFromFile(FXMLDocument, 'WhateverFile.xml');
// or XMLLoadFromAnsiString(FXMLDocument, SomeStringVar);
var
QryNode, Node: IXMLNode;
begin
QryNode := FXMLDocument.DocumentElement;
Node := SelectNode(QryNode, 'ShipTo');
if Assigned(Node) then
begin
QryNode := SelectNode(Node, '//Name');
if Assigned(QryNode) then
ShowMessage('ShipTo Name is ' + QryNode.FirstChild.Text)
else
ShowMessage('Name not found');
end;
end;
如果您愿意,XPath也能正常运行:
implementation
var
FXMLDocument: IXMLDocument;
// Somewhere along the line
FXMLDocument := CreateXMLDocument
XMLLoadFromFile(FXMLDocument, 'WhateverFile.xml');
// or XMLLoadFromAnsiString(FXMLDocument, SomeStringVar);
function GetShipTo: string;
var
QryNode: IXMLNode;
Node: IXMLNode;
NodeList: IXMLNodeList;
begin
Result := '';
QryNode := FXMLDocument.DocumentElement;
// The following also work:
// '//Address/Name'
// '//Name'
NodeList := XPathSelect(QryNode, '//ShipTo/Address/Name');
if NodeList.Length > 0 then
QryNode := NodeList.Item[0]
else
QryNode := nil;
if Assigned(QryNode) then
Result := QryNode.FirstChild.Text; // Now has 'SOME COMPANY'
end;
答案 1 :(得分:0)
我弄清楚我做错了什么:我必须指定整个相对路径,而不仅仅是我想要的孙子节点的名称。
从我上面的ProcessXML
示例中,我必须像这样填写Node2
:
Node2 := SelectNode(Node, 'Address/Name');
使用XPath,我必须通过XPathSelect(Node, 'Address/Name');