【问题标题】:How find element in xdocument and read next elements after them如何在 xdocument 中查找元素并在它们之后读取下一个元素
【发布时间】:2014-07-23 16:54:22
【问题描述】:

所以我有下一个 xml 文档:

<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>

那么我如何通过 ID 找到需要的项目并读取下一个值?提前致谢。

代码:

XDocument doc = XDocument.Load (filePath);

foreach (var item in doc.Descendants("ID"))
{
   if ((string)item.Element("ID") == "789") 
   {

       How to read Name "Simple Item"?
       How to read Count "6"?
       How to read Price "10"?

   }
}

【问题讨论】:

  • 到目前为止您介意展示您的代码吗?听起来你要求我们为你做这件事并给你代码。如果您需要一些入门帮助,我建议您查看XDocumentXMLDocument 和/或LINQ to XML。这些链接中有大量示例和文档,SO 上还有其他类似的问题,以及互联网上其他地方的示例/教程。
  • 请不要将代码添加为评论,编辑您的帖子并将其格式化,使其真正可读。
  • 在帖子中添加代码。谢谢

标签: c# linq-to-xml


【解决方案1】:

根据您的要求,您可以像这样格式化您的 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>

然后在代码中:

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;

这里的 id 是一个属性。读取它的值有两种方式:

//1º
foreach (var item in result.Elements())
{
    Console.WriteLine(item.Name + " = " + item.Value);
}

//2º - will print the element
Console.WriteLine(result);

【讨论】:

    【解决方案2】:

    这取决于您在找到这些值时想要做什么。这是使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多