如何将节点的内部文本和XML提取为字符串?

How to extract the inner text and XML of node as string?

我有以下 XML 结构:

<?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 中,我正在寻找一个函数,它将 returns 节点的内部文本和 XML 作为字符串。例如 <node1> 字符串应该是(如果可能包括缩进和换行符):

    <subnode1>
      <value1>101</value1>
      <value2>102</value2> 
      <value3>103</value3> 
    </subnode1>
    <subnode2>
      <value1>501</value1>
      <value2>502</value2> 
      <value3>503</value3> 
    </subnode2>

我在Delphi10.

中找不到这样的函数

有没有这个功能?

或者在 Delphi 10 中实现一个的最佳方法是什么?

您可以使用此功能进行提取。您只能为 1 个节点执行此操作。有了循环,你就可以随心所欲地获取两个标签之间的值了。

function Parse(Text, Sol, Sag: string): String;
begin
  Delete(Text, 1, Pos(Sol, Text) + Length(Sol) - 1);
  Result := Copy(Text, 1, Pos(Sag, Text) - 1);
end;

用途: XML:

 <test>Whosebug</test>

Delphi:

Parse(XML, '<test>', '</test>') //result: Whosebug

正确的处理方法是使用实​​际的XML库,例如Delphi的原生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属性 根据需要。

例如:

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;