gpt4 book ai didi

xml - delphi xmlchildnode 从父节点获取属性

转载 作者:数据小太阳 更新时间:2023-10-29 02:02:55 26 4
gpt4 key购买 nike

我正在尝试用 Delphi 编写 XML。

如果我给一个节点一个 xmlns 属性,该节点的子节点也会显示该属性,但随后为空。如何防止子节点显示该属性?

我用下面的代码测试

procedure TForm2.Button1Click(Sender: TObject);
var
RootNode, CurNode, PmtNode, PmtDetNode : IXMLNODE;
I:Integer;
begin
SepaDoc := Newxmldocument;
SepaDoc.Encoding := 'utf-8';
SepaDoc.Options := [doNodeAutoIndent];
RootNode := SepaDoc.AddChild('Document');
CurNode := RootNode.AddChild('Child1');
CurNode.Attributes['xmlns'] := 'apenootje';
CurNode := CurNode.AddChild('Child2');
CurNode := CurNode.AddChild('Child3');
SepaDoc.SaveToFile('D:\indir\testsepa.xml');
end;

这导致以下 XML

<?xml version="1.0" encoding="UTF-8"?>
-<Document> -<Child1 xmlns="apenootje">
-<Child2 xmlns="">
<Child3/>
</Child2>
</Child1>
</Document>

谢谢罗布·诺威

最佳答案

由于 Child1 的子元素不带有相同的命名空间,因此它必须未声明,这就是 Child2 持有空(默认)命名空间的原因。

这被称为 Namespace undeclaration

When an element carries the attribute xmlns="", the default namespace for that element and its descendants reverts to "no namespace": that is, unprefixed names are considered not to be in any namespace.

XML Namespaces 1.1 also introduces the option to undeclare other namespace prefixes. For example, if the attribute xmlns:p="" appears on an element, the namespace prefix p is no longer in scope (and therefore cannot be used) on that element or on its descendants, unless reintroduced by another namespace declaration

话虽这么说,修复很简单;在所有后续子节点上包含命名空间:

program SO20424534;

{$APPTYPE CONSOLE}

uses
ActiveX,
XMLdom,
XMLDoc,
XMLIntf,
SysUtils;

function TestXML : String;

var
RootNode,
CurNode : IXMLNODE;
Doc : IXmlDocument;
ns : String;

begin
Doc := Newxmldocument;
ns := 'apenootje';
Doc.Encoding := 'utf-8';
Doc.Options := [doNodeAutoIndent];
RootNode := Doc.AddChild('Document');
CurNode := RootNode.AddChild('Child1');
CurNode.DeclareNamespace('', ns);
CurNode := CurNode.AddChild('Child2', ns);
CurNode := CurNode.AddChild('Child3', ns);
Result := Doc.XML.Text;
end;

begin
try
CoInitialize(nil);
try
Writeln(TestXML);
finally
CoUninitialize;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end;

输出:

<?xml version="1.0"?>
<Document>
<Child1 xmlns="apenootje">
<Child2>
<Child3/>
</Child2>
</Child1>
</Document>

关于xml - delphi xmlchildnode 从父节点获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20424534/

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