Xml Path如何读取属性名称

时间:2017-04-20 04:46:50

标签: c# xml hibernate xml-parsing

我需要一些帮助。我有这样的xml:

<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
  </session-factory>
</hibernate-configuration>

我希望读取属性NAME和值(值介于

之间

我做过类似的事情

XPathNodeIterator iterator = nav.Select("/nh:hibernate-configuration/nh:session-factory/nh:property/@name", manager);
XPathNodeIterator iterator2 = nav.Select("/nh:hibernate-configuration/nh:session-factory/nh:property", manager);

while (iterator.MoveNext() && iterator2.MoveNext())
{
    var name = iterator.Current.Value;
    var property = iterator2.Current.Value;
}

但是在这种情况下只有一个迭代器可以用来获取名称和属性吗?

1 个答案:

答案 0 :(得分:0)

您只能使用第二个迭代器并使用GetAttribute()来读取name属性值:

XPathNodeIterator iterator2 = nav.Select("/nh:hibernate-configuration/nh:session-factory/nh:property", manager);
while (iterator2.MoveNext())
{
    var navigator = iterator.Current;
    var name = navigator.GetAttribute("name","");
    var property = navigator.Value;
}

无论如何,使用XmlDocument或使用LINQ-to-XML可以更简单地完成整个任务,如下所示:

var doc = XDocument.Load("path_to_your_xml.xml");
XNamespace d = "urn:nhibernate-configuration-2.2";
foreach(var prop in doc.Descendants(d+"property")
{
    var name = (string)prop.Attribute("name");
    var property = (string)prop;
}