GetElementById() not finding the tag?

北城以北 提交于 2019-12-23 08:08:51

问题


I have a valid XML file being read by the following .NET C# windows service. The tag in question (u1_000) is absolutely in the element:

<book id="u1_000" category="xyz"> 

Is there some reason the GetElementById() does not find the Book element with the tag? - thanks

XmlDocument doc = new XmlDocument();
doc.Load("C:\\j.xml");
XmlElement ee = doc.GetElementById("U1_000");

<book id="U1_000" category="web"> 

回答1:


If nothing else, perhaps use xpath as a backup:

string id = "u1_000";
string query = string.Format("//*[@id='{0}']", id); // or "//book[@id='{0}']"
XmlElement el = (XmlElement)doc.SelectSingleNode(query);



回答2:


Check the MSDN documentation for this method. In the sample below you can see how they establish what the ID is using the DOCTYPE. This may fix the problem for you.




回答3:


You need a DTD to establish which attribute on elements would consitute the unique id. In XML it isn't automatically assumed that the id attribute should be treated as a unique element ID.

In general "unDTDed" XML the getElementById is not very useful. It most cases the structure of the XML file being processed is understood (for example the root element is called books that contains a series of book elements) hence a typical access would look something like this:-

 XmlElement book = (XmlElement)doc.DocumentElement.SelectSingleNode("book[@ID='U1_000']");

If you really don't know the XML structure and/or the tag name of the element then the brute force search described in Marcs answer would work.



来源:https://stackoverflow.com/questions/2003185/getelementbyid-not-finding-the-tag

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