How do I access the child node values in my XML document?

為{幸葍}努か 提交于 2019-12-11 17:59:11

问题


I have a XmlString which contains multiple elements with their nodes.

ie

<Element>
    <AccountName>My Account Name</AccountName>
    <FullName>Edward Jones</FullName>
</Element>

I can access the Node names ie AccountName, FullName, but I can't access the values or they return blank. Here is my code.

Doc : IXMLDocument;
begin
  Doc := XMlDoc.LoadXMLData(XmlString);  
  Doc.DOMDocument.getElementsByTagName('Element').length;  // = 11  
  Doc.DOMDocument.getElementsByTagName('Element').item[2].childNodes[0].nodeName;  // = AccountName  
  Doc.DOMDocument.getElementsByTagName('Element').item[2].childNodes[0].nodeValue; 
end;  

There are 11 instances of the 'Element' in my XmlString so this checks out, the nodeName = AccountName which is what I expect. But the nodeValue is blank. Is there another way to pull the values? Does anyone know why the node values are blank?


回答1:


A guess: It looks like standard DOM API, so you could have a Text-node below the element nodes.

Doc.DOMDocument.getElementsByTagName('Element').item[2].childNodes[0].childNodes[0].nodeValue;



回答2:


You are dropping down all the way to the low-level DOM level. In that regard, @MizardX's response is correct - the text is contained in its own distinct child node that you have to access directly. However, since you are using IXMLDocument, you don't need to drop that far down. The IXMLNode interface is higher up and hides those details from you, providing easier access to nodes and their data, eg:

var
  Doc : IXMLDocument; 
  ElementNode, AccountNameNode, FullNameNode : IXMLNode;
  Count: Integer;
  NodeName, NodeText: String;
begin 
  Doc := LoadXMLData(XmlString);   
  ElementNode := Doc.DocumentElement;
  Count := ElementNode.ChildNodes.Count; // = 2

  AccountNameNode := ElementNode.ChildNodes[0];
  NodeName := AccountNameNode.NodeName;
  NodeText := AccountNameNode.Text;

  FullNameNode := ElementNode.ChildNodes[1];
  NodeName := FullNameNode.NodeName;
  NodeText := FullNameNode.Text;
end;   


来源:https://stackoverflow.com/questions/9980164/how-do-i-access-the-child-node-values-in-my-xml-document

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