6

I have an xml like this:

 <?xml version="1.0" encoding="utf-8" ?>
 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <reflection-optimizer use="false"/>
    <session-factory>
           <property name="XX">XX</property>
           <property name="XX">XX</property>
    </session-factory>  
  </hibernate-configuration>

I'm trying to select the property nodes using SelectNodes, and I've tried the following:

root.SelectNodes("property");
root.SelectNodes("//property");
root.SelectNodes("/session-factory/property");
root.SelectNodes("descendant::property");
root.LastChild.SelectNodes("child::property");

But all of them returns 0 nodes. Can anyone help me? Thanks.

user1486691
  • 267
  • 5
  • 18

3 Answers3

5

Take a look at this long answer:

Why is XmlNamespaceManager necessary?

It has to do with the namespace on the root node.

Community
  • 1
  • 1
Steen Tøttrup
  • 3,755
  • 2
  • 22
  • 36
1
var nsmgr = new XmlNamespaceManager(root.NameTable);
nsmgr.AddNamespace("x", "urn:nhibernate-configuration-2.2");

var nodes1 = root.SelectNodes("x:property", nsmgr);
var nodes2 = root.SelectNodes("/x:session-factory/x:property", nsmgr);

Frank Rem
  • 3,632
  • 2
  • 25
  • 37
0

I would recomend you to use LINQ to XML

    var xml = XDocument.Parse(
    @"<?xml version=""1.0"" encoding=""utf-8"" ?>
    <hibernate-configuration xmlns=""urn:nhibernate-configuration-2.2"">
    <reflection-optimizer use=""false""/>
    <session-factory>
    <property name=""XX"">XX</property>
    <property name=""XX"">XX</property>
    </session-factory>  
    </hibernate-configuration>");
    var properties = xml.Descendants().Where(p=>p.Name.LocalName.Equals("property")).ToList();

Check msdn for more info here: http://msdn.microsoft.com/en-us/library/bb943906.aspx

Uriil
  • 11,948
  • 11
  • 47
  • 68
  • 1
    Thanks for your reply. I have it working using LINQ to XML, but I still want to figure out what I'm doing wrong with SelectNodes. – user1486691 Jul 27 '12 at 15:00