2012-05-15 89 views
-1

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

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

我可以读everyting,但我的问题是我不能单独选择。

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

我该如何阅读和加入他们?

回答

0

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();