【问题标题】:Xml Reader Read TagsXml Reader 读取标签
【发布时间】:2012-05-15 11:06:35
【问题描述】:

我必须读取 xml 文件。我做到了,但我遇到了问题。 我有这样的xml

  <?xml version="1.0" encoding="windows-1254" ?> 
- <Xm>
- <Products>
  <Product_No>NT-7</Product_No> 
  <Stok>1</Stok> 
  <Product_Details>something</Product_Details> 
  <Desi>0,2</Desi> 
- <Variant>
  <VariantAd>size</VariantAd> 
  <Options>68 cm</Options> 
  </Variant>
  </Products>
- <Products>
  <Product_No>NT-15</Product_No> 
  <Stok>1</Stok> 
  <Product_Details>something</Product_Details> 
  <Desi>0,2</Desi> 
- <Variant>
  <VariantAd>size</VariantAd> 
  <Options>68 cm</Options> 
  <Options>74 cm</Options> 
  </Variant>
  </Products>
  </Xm>

我可以阅读所有内容,但我的问题是我无法单独选择。

  <Options>68 cm</Options> 
  <Options>74 cm</Options> 

我不能一起读。我需要一起阅读并将它们作为字符串加入。

System.Xml.XmlNodeList lst = root.GetElementsByTagName("Product_No");
foreach (System.Xml.XmlNode n in lst)
{
    Product_No.Add(n.InnerText);
}
lst = root.GetElementsByTagName("Stok");
foreach (System.Xml.XmlNode n in lst)
{
    Stok.Add(n.InnerText);
}
lst = root.GetElementsByTagName("Product_Details");
foreach (System.Xml.XmlNode n in lst)
{
    Product_Details.Add(n.InnerText);
}
lst = root.GetElementsByTagName("Options");
foreach (System.Xml.XmlNode n in lst)
{
    Options.Add(n.InnerText);
}

我如何阅读和加入他们?

【问题讨论】:

    标签: c# xml xmlreader


    【解决方案1】:

    Linq2Xml 让生活更轻松

    var items = xDoc.Descendants("Products")
        .Select(p => new
        {
            ProductNo=p.Element("Product_No").Value,
            Stok = p.Element("Stok").Value,
            ProductDetails = p.Element("Product_Details").Value,
            Options = String.Join(";",p.Descendants("Options").Select(o=>o.Value))
        })
        .ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多