开发者

C# XPath id() not working?

I'm using C# and I'm stumped. Does it just not support id()? I have a large XML file, about 4-5 of them at ~400kb, so I need some speed and performance wherever I can get it.

I use XmlDocument.SelectSingleNode开发者_高级运维("id('blahblahblah')") and it doesn't get the node by id. Am I going crazy or is it that C# XPath just doesn't support id()?


Use XmlDocument.GetElementById to get the XmlElement with the specified ID, e.g.:

XmlElement elem = doc.GetElementById("blahblahblah");

This works only with documents specifying a DTD though:

Attributes with the name "ID" are not of type ID unless so defined in the DTD.


In case your document does not have a DTD, you could use an XPath expression to select the node with the id attribute set to your ID:

XmlElement elem = doc.SelectSingleNode("//*[@id='blahblahblah']");


xmlDocument.GetElementById("blahblahblah")

might be a better option.


"Official" XPath recommendation says that:

The id function selects elements by their unique ID

Where

An element node may have a unique identifier (ID). This is the value of the attribute that is declared in the DTD as type ID. No two elements in a document may have the same unique ID. If an XML processor reports two elements in a document as having the same unique ID (which is possible only if the document is invalid) then the second element in document order must be treated as not having a unique ID.

NOTE: If a document does not have a DTD, then no element in the document will have a unique ID.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜