Read a XML file using C#.Net
-
Tuesday, January 08, 2013 9:04 AM
<ns0:BookStore xmlns:ns0=URI
- <ns1:BookDetails xmlns:ns1= URI1
<ns1:Name>ns0:Name_0</ns1:Name>
<ns1:PurchaseDate>1999-05-31T13:20:00.000-05:00</ns1:PurchaseDate>
<ns1:SlNo>10</ns1:SlNo>
<ns1:Id>8563452</ns1:Id>
<ns1:Code>2631</ns1:Code>
<ns1:Price>800.25</ns1:Price>
</ns1:BookDetails>- <ns2:BookDetails xmlns:ns2= URI1
<ns2:Name>ns0:Name_0</ns2:Name>
<ns2:PurchaseDate>1999-05-31T13:20:00.000-05:00</ns2:PurchaseDate>
<ns2:SlNo>20</ns2:SlNo>
<ns2:Id>8962596</ns2:Id>
<ns2:Code>2563</ns2:Code>
<ns2:Price>589.26</ns2:Price>
</ns2:BookDetails>- <ns3:BookDetails xmlns:ns3= URI1
<ns3:Name>ns0:Name_0</ns3:Name>
<ns3:PurchaseDate>1999-05-31T13:20:00.000-05:00</ns3:PurchaseDate>
<ns3:SlNo>30</ns3:SlNo>
<ns3:Id>1589652</ns3:Id>
<ns3:Code>1589</ns3:Code>
<ns3:Price>125.00</ns3:Price>
</ns3:BookDetails>
</ns0:BookStore>I want to extarct the below 3 results from above XML.
Could you please help me, how to Extarct the below values using C# Window Application?
1: Combination of <ns1:PurchaseDate> + <ns1:SlNo> + <ns1:Id>
2: Combination of <ns2:PurchaseDate> + <ns2:SlNo> + <ns2:Id>
3: Combination of <ns3:PurchaseDate> + <ns3:SlNo> + <ns3:Id>
All Replies
-
Tuesday, January 08, 2013 10:27 AM
Consider to show us well-formed XML input, then we can post working code. Currently your posted sample is not well-formed XML as attribute values are not properly quoted (as in xmlns:ns= URI1).
And whether it is a Windows Application or some other .NET code, with .NET and C# since .NET 3.5 the preferred way to read out data from an XML document is LINQ to XML :
XDocument doc = XDocument.Load("input.xml"); XNamespace ns0 = "URI"; XNamespace ns1 = "URI1"; var data = from detail in doc.Element(ns0 + "BookStore").Elements(ns1 + "BookDetails") select new { date = (DateTime)detail.Element(ns1 + "PurchaseDate"), slNo = (int)detail.Element(ns1 + "SlNo"), id = (int)detail.Element(ns1 + "Id") }; List<string> threeValues = (from record in data.Take(3) select string.Format("Date:{0}, SlNo: {1}, Id: {2}", record.date, record.slNo, record.id)).ToList();
That example first shows how to read out typed values like a DateTime. Of course if you know you only want the string contents you could directly take the string in one "from .. select" query.
MVP Data Platform Development My blog

