gpt4 book ai didi

xml - 德尔福 XE 和 OmniXML : Using SelectNode()?

转载 作者:行者123 更新时间:2023-12-02 20:55:50 28 4
gpt4 key购买 nike

我得到了以下 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 ?根据OmniXMLUtils.pas中的帮助, SelectNode将选择一个可能比下面不止一级的节点。肯定有一个<Name>节点。甚至试图通过 XPathSelect(Node1, 'Name'); 找到节点返回一个空列表。我是否以某种方式错误地使用了 OmniXML?是否可以调用 <Name>节点,无需先选择 <Address>节点?

最佳答案

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;

关于xml - 德尔福 XE 和 OmniXML : Using SelectNode()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513917/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com