How to find an XPath query to Element/Element without namespaces (XmlSerializer, fragment)?

Posted by Veksi on Stack Overflow See other posts from Stack Overflow or by Veksi
Published on 2013-10-22T21:33:37Z Indexed on 2013/10/22 21:54 UTC
Read the original article Hit count: 211

Filed under:
|
|
|
|

Assume this simple XML fragment in which there may or may not be the xml declaration and has exactly one NodeElement as a root node, followed by exactly one other NodeElement, which may contain an assortment of various number of different kinds of elements.

<?xml version="1.0">
<NodeElement xmlns="xyz">
    <NodeElement xmlns="">
        <SomeElement></SomeElement>
    </NodeElement>
</NodeElement>

How could I go about selecting the inner NodeElement and its contents without the namespace? For instance, "//*[local-name()='NodeElement/NodeElement[1]']" (and other variations I've tried) doesn't seem to yield results.

As for in general the thing that I'm really trying to accomplish is to Deserialize a fragment of a larger XML document contained in a XmlDocument. Something like the following

 var doc = new XmlDocument();
 doc.LoadXml(File.ReadAllText(@"trickynodefile.xml")); //ReadAllText to avoid Unicode trouble.
 var n = doc.SelectSingleNode("//*[local-name()='NodeElement/NodeElement[1]']");
 using(var reader = XmlReader.Create(new StringReader(n.OuterXml)))
 {
    var obj = new XmlSerializer(typeof(NodeElementNodeElement)).Deserialize(reader);

I believe I'm missing just the right XPath expression, which seem to be rather elusive. Any help much appreciated!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET