Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLDocument GetElementByID returning null

I'm trying to get an element of a xml by using the function GetElementById, but the function is always returning null.

//get xml text from a web service
string xml = aS.createTree();
XmlDocument tree = new XmlDocument();
tree.LoadXml(xml);

//get all nodes with the tag name "item"
XmlNodeList node = tree.GetElementsByTagName("item");
//just for test to see if i could get the attribute value which returns the expected
string idTemp = node[0].Attributes["ID"].Value;
XmlElement elem = tree.GetElementById("1");

elem is always returning null. Can you guys help me out?

By the way this is the xml that i'm trying to parse:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE tree [
   <!ELEMENT tree ANY>
   <!ELEMENT item ANY>
   <!ATTLIST item id ID #REQUIRED>
]>
<tree>
   <item id="1">
       <item id="2"></item>
   </item>
   <item id="5">
       <item id="6"></item>
       <item id="7">
           <item id="8">
               <item id="10">
                   <item id="11"></item>
               </item>
           </item>
           <item id="9"></item>
       </item>
   </item>
</tree>
like image 391
Caixotim Avatar asked Jun 04 '26 13:06

Caixotim


2 Answers

Just change ID to id:

string idTemp = node[0].Attributes["id"].Value;

but note that:

XmlDocument.GetElementByIdfrom MSDN:

The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return null.

like image 90
Ria Avatar answered Jun 06 '26 01:06

Ria


As far as I know the id att cannot start with a number. Can you try some thing like id="_1" and see how it works.

like image 31
Onur Topal Avatar answered Jun 06 '26 02:06

Onur Topal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!