XML如何使用XPath

问题描述:

我有下面的XML,如下图所示,选择子元素:XML如何使用XPath

XML File

但我不能为我的生命,让任何代码选择在<ArrayOfHouse>之间的房子元素。

将有一个以上的House元素一旦我设法得到它选择一个,这里是到目前为止我的代码:

// Parse the data as an XML document 
XDocument xmlHouseResults = XDocument.Parse(houseSearchResult); 

// Select the House elements 
XPathNavigator houseNavigator = xmlHouseResults.CreateNavigator(); 

XPathNodeIterator nodeIter = houseNavigator.Select("/ArrayOfHouse/House"); 

// Loop through the selected nodes 
while (nodeIter.MoveNext()) 
{ 

    // Show the House id, as taken from the XML document 
    MessageBox.Show(nodeIter.Current.SelectSingleNode("house_id").ToString()); 
} 

我得到XML流,因为我已经管理在上面显示的MessageBox中显示数据,但我无法到达各个房屋。

+2

为什么不使用XML序列化?由于这种XML显然是通过XML序列化生成的,所以它可能是最自然的解决方案... – 2012-02-03 12:50:55

+0

查看使用[XPath Visualizer](http://xpathvisualizer.codeplex.com/)来测试XML上的XPath查询。 – Lukazoid 2012-02-03 13:01:54

您可以选择在众议院节点是这样的:

var houses = XDocument.Parse(houseSearchResult).Descendants("House"); 
foreach(var house in houses) 
{ 
    var id = house.Element("house_id"); 
    var location = house.Element("location"); 
} 

或者您可以使用Select直接得到一个强类型的对象:

var houses = XDocument.Parse(houseSearchResult) 
         .Descendants("House") 
         .Select(x => new House 
            { 
             Id = x.Element("house_id"), 
             Location = x.Element("location") 
            }); 

这个假设存在一个类House与属性IdLocation

此外,请务必考虑Thomas Levesque使用XML序列化的建议。

+0

感谢您的提示,我将如何循环访问每个房屋以获得''或'' – Luke 2012-02-03 13:00:06

+0

@Coulton:请参阅更新。 – 2012-02-03 13:04:39

使用XPath时,您需要使用XmlNamespaceManager,但是因为您有XDocument,您可以简单地使用LINQ to XML轴方法,例如,

XNamespace df = XmlHouseResults.Root.Name.Namespace; 

foreach (XElement house in XmlHouseResults.Descendants("df" + "House")) 
{ 
    MessageBox.Show((string)house.Element("df" + "house_id")); 
}