XMLDocument GetElementByID返回null

时间:2012-07-16 09:39:21

标签: c# xml null getelementbyid xmldocument

我正在尝试使用函数GetElementById获取xml的元素,但该函数始终返回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始终返回null。你能帮助我吗?

顺便说一下,这是我试图解析的xml:

<?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>

3 个答案:

答案 0 :(得分:3)

只需将ID更改为id

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

但请注意:

来自MSDN的

XmlDocument.GetElementById

  

DOM实现必须具有定义哪些属性属于ID类型的信息。虽然可以在XSD架构或DTD中定义类型ID的属性,但此版本的产品仅支持在DTD中定义的那些。除非在DTD中定义,否则名称为“ID”的属性不是ID类型。不知道属性是否为ID类型的实现应该返回null。

答案 1 :(得分:2)

据我所知,id att不能以数字开头。你可以试试像id="_1"这样的东西,看看它是如何运作的。

答案 2 :(得分:0)

https://www.w3schools.com/tags/att_global_id.asp

  

HTML 4.01和HTML5之间的差异

     

注意:HTML 4.01对id值的内容有更大的限制(例如,在HTML 4.01中,id值不能以数字开头)。