XMLDocument的GetElementByID方法返回null。

3

我正在尝试使用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个回答

4

只需将 ID 改为 id

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

但请注意:
来自MSDN的XmlDocument.GetElementById
DOM实现必须具有定义哪些属性属于ID类型的信息。虽然ID类型的属性可以在XSD模式或DTD中定义,但是该产品版本仅支持在DTD中定义的属性。除非在DTD中定义,“ID”名称的属性不属于ID类型。如果无法确定属性是否为ID类型,则应返回null。

3
据我所知,id属性不能以数字开头。你可以尝试使用id="_1"之类的内容,看看是否可行。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接