有人可以帮助我从<a n="Formatted Name" v="Test Project 1"/>
这些似乎不是属性。它们是什么以及如何获得我需要的文本?
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item Id="814135481" Rank="1"><a n="Formatted Name" v="Test Project 1"/></item>
<item Id="814135882" Rank="2"><a n="Formatted Name" v="Test Project 2"/></item>
<item Id="814135908" Rank="3"><a n="Formatted Name" v="Test Project 3"/></item>
</items>
RootNode := XMLDoc.DocumentElement;
for I := 0 to RootNode.ChildNodes.Count-1 do
begin
//
end;
RootNode.ChildNodes [I] .AttributeNodes [N]
会给我项目的属性列表,但我不知道如何提取这些值
<a n="Formatted Name" v="Test Project 1"/>
用于理解ANSWER的XML:
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item Id="814135481" Rank="1">
<a n="Formatted Name" v="Test Project 1"/>
</item>
<item Id="814135882" Rank="2">
<a n="Formatted Name" v="Test Project 2"/>
</item>
<item Id="814135908" Rank="3">
<a n="Formatted Name" v="Test Project 3"/>
</item>
</items>
答案 0 :(得分:4)
它们是a
代码中的属性,但a
代码是item
代码的子代,这些代码是items
代码的子代。您的for
循环只会为您提供一个结果,items
节点。
您可以使用嵌套循环处理此问题,也可以use an xpath query获取与items/item/a
匹配的所有标记的集合。然后你看看那些属性。
答案 1 :(得分:0)
原来这比我想象的容易。我读错了XML:
RootNode.ChildNodes [I] .ChildNodes [0] .AttributeNodes [1]。文本;
答案 2 :(得分:0)
最简单的方法是使用IXMLDOMDocument
和XPath
;
uses
msxml;
const
TestXML = '<?xml version="1.0" encoding="utf-8" ?>' +
'<items><item Id="814135481" Rank="1">' +
'<a n="Formatted Name" v="Test Project 1"/></item>' +
'<item Id="814135882" Rank="2">' +
'<a n="Formatted Name" v="Test Project 2"/>' + '</item>' +
'<item Id="814135908" Rank="3">' +
'<a n="Formatted Name" v="Test Project 3"/>' +
'</item></items>';
var
Doc: IXMLDOMDocument;
NodeList: IXMLDOMNodeList;
ANode: IXMLDOMNode;
i: Integer;
begin
Doc := CoDOMDocument.Create;
Doc.loadXML(TestXML);
// Select all of the <a> nodes only
NodeList := Doc.selectNodes('//a');
// Error checking omitted. Should test for `NodeList <> nil` before use here.
for i := 0 to NodeList.length - 1 do
// Should really use another node here as an intermediate
// step, to make sure that getNamedItem succeeded. Omitted
// for brevity
Memo1.Lines.Add(Node.attributes.getNamedItem('v').nodeValue);
end;