C# XML如何使用XPath选择子元素
我得到了以下XML,如下图所示: 但就我的一生而言,我无法获得任何代码来选择C# XML如何使用XPath选择子元素,c#,asp.net,xml,xpath,nodes,C#,Asp.net,Xml,Xpath,Nodes,我得到了以下XML,如下图所示: 但就我的一生而言,我无法获得任何代码来选择之间的房屋元素 一旦我设法让它选择一个元素,就会有多个房子元素,以下是我目前的代码: // Parse the data as an XML document XDocument xmlHouseResults = XDocument.Parse(houseSearchResult); // Select the House elements XPathNavigator houseNavigator = xmlHo
之间的房屋元素
一旦我设法让它选择一个元素,就会有多个房子元素,以下是我目前的代码:
// 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")
});
这假设存在一个属性为Id
和Location
的类House
另外,请务必考虑Thomas Levesque关于使用XML序列化的建议。对于XPath,您需要使用XmlNamespaceManager
,但是由于您有XDocument
,您可以简单地使用LINQ到XML轴方法,例如
XNamespace df = XmlHouseResults.Root.Name.Namespace;
foreach (XElement house in XmlHouseResults.Descendants("df" + "House"))
{
MessageBox.Show((string)house.Element("df" + "house_id"));
}
为什么不使用XML序列化?由于此XML显然是通过XML序列化生成的,因此它可能是最自然的解决方案……请看一下如何使用XML测试XPath查询。感谢您的提示,然后我将如何在每家每户中循环获取
或