我有以下XML,如下图所示:



但是我无法终生,获取任何代码来选择<ArrayOfHouse>之间的house元素。

一旦我设法选择一个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中显示数据,但是我无法到达各个地方。

最佳答案

您可以像这样选择房屋节点:

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")
                                   });


假定存在具有属性HouseId的类Location

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

10-07 12:53
查看更多