Select node by node text
I have to following XML file:
<root xmlns="http://someurl/element" xmlns:text="http://someurl/text">
<elements>
<element>
<Id>text:SOME_ID</Id>
<!-- some other elements -->
</element>
<element>
<!-- some other elements -->
<reference>
<link ref="text:SOME_ID" />
</reference>
</element>
</elements>
</root>
I want to select all child elements of the elment node which have the element Id=text:SOME_ID, how can i get it using xmldocument metho开发者_C百科d
From your question it is not entirely clear to me what you want to select but I assume you want to select <element>
having child <Id>
with content text:SOME_ID
.
If you insist on using XmlDocument
you can use it like this:
IEnumerable<XPathNavigator> GetElements(String xml, String id) {
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
namespaceManager.AddNamespace("ns", "http://someurl/element");
var navigator = xmlDocument.CreateNavigator();
var xPath = "//ns:element/ns:Id[. = '" + id + "']/..";
return navigator.Select(xPath, namespaceManager).Cast<XPathNavigator>();
}
However, I recommend using LINQ to XML:
IEnumerable<XElement> GetElements(String xml, String id) {
XNamespace ns = "http://someurl/element";
var xDocument = XDocument.Parse(xml);
return xDocument
.Descendants(ns + "element")
.Where(element => (String) element.Element(ns + "Id") == id);
}
精彩评论