C# 如何在xdocument中查找元素并读取后面的元素
下面是下一个xml文档:C# 如何在xdocument中查找元素并读取后面的元素,c#,linq-to-xml,C#,Linq To Xml,下面是下一个xml文档: <Items> <Item> <ID>123</ID> <Name>Super Item</Name> <Count>1</Count> <Price>45</Price> </Item> <Item>
<Items>
<Item>
<ID>123</ID>
<Name>Super Item</Name>
<Count>1</Count>
<Price>45</Price>
</Item>
<Item>
<ID>456</ID>
<Name>not super Item</Name>
<Count>10</Count>
<Price>5</Price>
</Item>
<Item>
<ID>789</ID>
<Name>Simple Item</Name>
<Count>6</Count>
<Price>10</Price>
</Item>
</Items>
这取决于找到这些值时要做什么。以下是使用foreach循环查找具有指定ID的项并返回其名称的常规方法:
private string GetItemName(string _id)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load("myXmlFile.xml");
foreach (XmlNode item in xDoc.SelectNodes("/Items/Item"))
{
if (item.SelectSingleNode("ID").InnerText == _id)
{
// we found the item! Now what do we do?
return item.SelectSingleNode("Name").InnerText;
}
}
return null;
}
根据您的要求,您可以将xml格式化如下:
<Items>
<Item id="123">
<Name>Super Item</Name>
<Count>1</Count>
<Price>45</Price>
</Item>
<Item id="456">
<Name>not super Item</Name>
<Count>10</Count>
<Price>5</Price>
</Item>
<Item id="789">
<Name>Simple Item</Name>
<Count>6</Count>
<Price>10</Price>
</Item>
</Items>
这里的id是一个属性。要通过两种方式读取其值:
//1º
foreach (var item in result.Elements())
{
Console.WriteLine(item.Name + " = " + item.Value);
}
//2º - will print the element
Console.WriteLine(result);
到目前为止,您是否介意显示您的代码?听起来你是在要求我们为你做这件事,然后给你密码。如果您在开始时需要一些帮助,我建议您调查和/或。这些链接中有大量的示例和文档,以及其他类似于此处的问题,以及internet上其他地方的示例/教程。请不要将代码添加为注释,编辑您的帖子并在那里设置格式,以便其实际可读。在帖子中添加代码。谢谢
int yourId = 456;
XDocument doc = XDocument.Load("test.xml");
var result = from el in doc.Root.Elements("Item")
where el.Attribute("id").Value == yourId.ToString()
select el;
//1º
foreach (var item in result.Elements())
{
Console.WriteLine(item.Name + " = " + item.Value);
}
//2º - will print the element
Console.WriteLine(result);