Delphi IXMLNode FindNode不使用命名空间
这是我的代码的一个简短示例,但很好地理解了我的问题 我有这样一个xml文件:Delphi IXMLNode FindNode不使用命名空间,xml,delphi,namespaces,Xml,Delphi,Namespaces,这是我的代码的一个简短示例,但很好地理解了我的问题 我有这样一个xml文件: <root xmlns:h="http://www.w3.org/TR/html4/"> <h:data> <first>one</first> <second>two</second> </h:data> </root> 使用此xml文件可以很好地工作,但不幸的是,我有一个无法删除的命名空间: <
<root xmlns:h="http://www.w3.org/TR/html4/">
<h:data>
<first>one</first>
<second>two</second>
</h:data>
</root>
使用此xml文件可以很好地工作,但不幸的是,我有一个无法删除的命名空间:
<root xmlns:h="http://www.w3.org/TR/html4/">
<data>
<first>one</first>
<second>two</second>
</data>
</root>
一
二
我正在处理一个复杂的xml文件,我需要“FindNode”与名称空间一起工作
提前谢谢 您需要使用名称空间重载:
xnode := Doc.DocumentElement.ChildNodes.FindNode('h:data', 'http://www.w3.org/TR/html4/');
这将返回您正在查找的节点
如果要搜索根目录中的所有属性并读取名称空间,则可以执行以下操作:
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;
嗨,灰质,它工作了!但现在我的疑问是。我知道父节点在本例中是根节点,但如何获取名称空间“h”和url“”。@user1727336您需要知道名称空间是什么。如果您不知道名称空间,那么可以通过访问根目录上的属性来检索名称空间列表,但是您需要扫描整个xml文件,以查看正在使用哪些名称空间以及它们在哪里。您是否总是希望检索根上名为data的节点,而不考虑名称空间?
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;