Search code examples
c#xmlxmlreader

Xml Reader Read Tags


I have to read xml file. I did it but i had a problem. I have xml like this

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

I can read everyting, but my problem is i cant seperate options.

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

I cant read it together. I need to read it together and join them as string.

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

How can i read and join them ?


Solution

  • Linq2Xml can make the life easier

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