问题描述
我具有以下XML结构:
I have the following XML structure:
<?xml version="1.0"?>
<main>
<node1>
<subnode1>
<value1>101</value1>
<value2>102</value2>
<value3>103</value3>
</subnode1>
<subnode2>
<value1>501</value1>
<value2>502</value2>
<value3>503</value3>
</subnode2>
</node1>
</main>
在Delphi中,我正在寻找一个函数,该函数以字符串形式返回节点的内部文本和XML.例如,对于< node1>
,字符串应为(如果可能,包括缩进和换行符):
In Delphi I am looking for a function which returns the inner text and XML of a node as a string. For example for <node1>
the string should be (if possible including indents and line breaks):
<subnode1>
<value1>101</value1>
<value2>102</value2>
<value3>103</value3>
</subnode1>
<subnode2>
<value1>501</value1>
<value2>502</value2>
<value3>503</value3>
</subnode2>
我在Delphi 10中找不到这样的功能.
I cannot find such a function in Delphi 10.
有这样的功能吗?
或者在Delphi 10中实现一种最佳方法是什么?
Or what is the best approach to implement one in Delphi 10?
推荐答案
解决此问题的正确方法是使用实际的XML库,例如Delphi的本机 TXMLDocument
组件或 IXMLDocument
接口(或可用于Delphi的任意数量的第三方XML库).您可以将XML加载到其中,然后找到 IXMLNode
作为< node1>
元素(或所需的任何元素),然后阅读其 XML
属性.
The correct way to handle this is to use an actual XML library, such as Delphi's native TXMLDocument
component or IXMLDocument
interface (or any number of 3rd party XML libraries that are available for Delphi). You can load your XML into it, then find the IXMLNode
for the <node1>
element (or whichever element you want), and then read its XML
property as needed.
例如:
uses
..., Xml.XMLIntf, Xml.XMLDoc;
var
XML: DOMString;
Doc: IXMLDocument;
Node: IXMLNode;
begin
XML := '<?xml version="1.0"?><main><node1>...</node1></main>';
Doc := LoadXMLData(XML);
Node := Doc.DocumentElement; // <main>
Node := Node.ChildNodes['node1'];
XML := Node.XML;
ShowMessage(XML);
end;
或者:
uses
..., Xml.XMLIntf, Xml.xmldom, Xml.XMLDoc;
var
XML: DOMString;
Doc: IXMLDocument;
Node: IXMLNode;
XPath: IDOMNodeSelect;
domNode: IDOMNode;
begin
XML := '<?xml version="1.0"?><main><node1>...</node1></main>';
Doc := LoadXMLData(XML);
XPath := Doc.DocumentElement.DOMNode as IDOMNodeSelect;
domNode := XPath.selectNode('/main/node1');
Result := TXMLNode.Create(domNode, nil, (Doc as IXmlDocumentAccess).DocumentObject);
XML := Node.XML;
ShowMessage(XML);
end;
这篇关于如何提取节点的内部文本和XML作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!