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

我的梦境 提交于 2020-12-10 08:00:27

问题


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>

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>

I cannot find such a function in Delphi 10.

Is there such a function?

Or what is the best approach to implement one in Delphi 10?


回答1:


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.

For example:

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;

Or:

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;



回答2:


You can use this function to extract. You can only do it for 1 node. With the loop, you can get the value between two tags as you wish.

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;

Use of: XML:

 <test>Stackoverflow</test>

Delphi:

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


来源:https://stackoverflow.com/questions/62802155/how-to-extract-the-inner-text-and-xml-of-node-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!