gpt4 book ai didi

xml - Delphi IXMLNode FindNode 不适用于命名空间

转载 作者:行者123 更新时间:2023-12-03 19:41:07 29 4
gpt4 key购买 nike

这是我的代码的一个简短示例,但很好理解我的问题。

我有一个像这样的 xml 文件:

<root xmlns:h="http://www.w3.org/TR/html4/">
<h:data>
<first>one</first>
<second>two</second>
</h:data>
</root>

这是我在delphi中的代码:
procedure TForm1.Button1Click(Sender: TObject);
var
xnode: IXMLNode;
Doc: TXMLDocument;
FileName : String;
begin
XMLFileName := 'D:\doc.xml';
Doc := TXMLDocument.Create(Application);

Doc.LoadFromFile(XMLFileName);
Doc.Active := true;
// not working xnode is nil
xnode := Doc.DocumentElement.ChildNodes.FindNode('data');

//this also doesn't work, xnode is also nil

xnode := Doc.DocumentElement.ChildNodes.FindNode('h:data');
Doc.Free;
end;

使用此 xml 文件可以正常工作,但不幸的是,我有一个无法删除的命名空间:
<root xmlns:h="http://www.w3.org/TR/html4/">
<data>
<first>one</first>
<second>two</second>
</data>
</root>

我正在处理一个复杂的 xml 文件,我需要“FindNode”与 NameSpace 一起使用。

提前致谢 !

最佳答案

您需要使用命名空间重载:

xnode := Doc.DocumentElement.ChildNodes.FindNode('h:data', 'http://www.w3.org/TR/html4/');

这将返回您正在寻找的节点。

如果要搜索根中的所有属性并读取 namespace ,则可以执行以下操作:
type
TNamespaceAttribute = record
namespace: string;
namespaceurl: string;
end;

var
attrlist: array of TNamespaceAttribute;
cntr: Integer;
begin
// This will read in the list of namespaces
for cntr := 0 to Doc.DocumentElement.AttributeNodes.Count - 1 do
begin
if Doc.DocumentElement.AttributeNodes[cntr].Prefix = 'xmlns' then
begin
// Don't like doing this but it gets the idea across
SetLength(attrlist, Length(attrlist)+1);
attrlist[High(attrlist)].namespace := Doc.DocumentElement.AttributeNodes[cntr].LocalName;
attrlist[High(attrlist)].namespaceUrl := Doc.DocumentElement.AttributeNodes[cntr].Text;
end;
end;

// You can iterate through them like this to get all of the instances
// of the data node, regardless of the namespace
for cntr := Low(attrlist) to High(attrlist) do
begin
xnode := Doc.DocumentElement.ChildNodes.FindNode(attrlist[cntr].namespace+':data', attrlist[cntr].namespaceurl);
// Do something here
end;
end;

关于xml - Delphi IXMLNode FindNode 不适用于命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23524793/

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