tags:

views:

82

answers:

3

I have a XML code like this:

<?xml version="1.0" encoding="utf-8" ?> 
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;

    <Grid>
            <Label/>
            <Label/>
            <Label/>
    </Grid>
</Window>

In code, this is represented as a XML Document. The question is in the code that follows:

public XmlNodeList GetAllChildrenOfName(XmlNode parent, string childName) 
{
    string xpath = childName;
    //string xpath = "/" + childName;
    //string xpath = "//" + childName;

    return parent.SelectNodes(xpath);
}

If I call the method for the grid xml node (GetAllChildrenOfName(gridNode,"Label")) from the xml code above, it does not return the expected list of 3 labels for any of the suggested xpath values.

Any guesses, how should the xpath look like?

Thanks

+3  A: 

child:: is the default axis, so if parent is the Grid, then parent.SelectNodes("Label") should work, assuming that Label is in the default namespace. If you have xml-namespaces you'll need to qualify it by creating a namespace manager:

var nsmgr = new XmlNamespaceManager(parent.OwnerDocument.NameTable);
nsmgr.AddNamespace("foo","blah/your/namespace");
return parent.SelectNodes("foo:Label", nsmgr);
Marc Gravell
+1  A: 

This worked for me:

static int Main(string[] args)
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.LoadXml("<Grid><Label /><Label /><Label /></Grid>");
    Response.Write(GetAllChildrenOfName(xDoc.FirstChild, "Label").Count.ToString());
}

public XmlNodeList GetAllChildrenOfName(XmlNode parent, string childName)
{
    string xpath = childName;
    return parent.SelectNodes(xpath);
}

And the output was 3.

Naeem Sarfraz
A: 

Because I did not find why the sollution, that works for others, does not work for me, I simply used my own method like this:

private List<XmlNode> SelectNamedChildNodes(XmlNode parent, string name)
        {
            List<XmlNode> list = new List<XmlNode>();
            foreach (XmlNode node in parent.ChildNodes)
            {
                if (node.Name == name) list.Add(node);
            }
            return list;
        }

It is possible to work with the result just the same way as with the XmlNodeList.

Gal