2
Reply

C# using linq to parse xml

dc

dc

Aug 28 2012 11:37 PM
1.8k
I would like to parse an xml file using linq in a C#2010 application. Listed below you will find an example of an xml file I want to parse. I would like to use the  code listed  below to parse the an xml file. Thus I am wondering if you can show me how to use the code I listed below to parse the xml displayed below and/or show me code that will accomplish this goal?


The following is the code:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
  static void Main()
  {
  XDocument document = XDocument.Load(@"d:\test.xml");
  var priceInfo = from e in document.Descendants("MPrice").Elements("Price")
  let start = DateTime.Parse(e.Descendants("StartDt").FirstOrDefault().Value)
  let end = DateTime.Parse(e.Descendants("EndDt").FirstOrDefault().Value)
  where start < DateTime.Now && end > DateTime.Now
  select new { Id = e.Parent.Element("Id").Value, ListPrice = e.Element("ListPrice").Value };
  Console.WriteLine(priceInfo.FirstOrDefault().Id);
  Console.WriteLine(priceInfo.FirstOrDefault().ListPrice);
  }
}
The following is the metatag:
<ns2:RetsubPack serviceSuccessful="true" returnCode="0" xmlns:ns2="http://test1/test">
  <statusDescription>Package Details retrieved Successfully</statusDescription>
  <PackageDetails>
  <Type>type2</Type>
  <Category>dog</Category>
  <ContName>Co 1</ContgName>
  <TotalTrans>0</TotalTrans>
  </PackageDetails>
  <NumberOfDocuments>3</NumberOfDocuments>
  <subDocuments attachmentId="xx1">
  <DocumentMetadata>
  <DocumentTypeCode>Spreadsheet1</DocumentTypeCode>
  <PackageId>pkg1</PackageId>
  </DocumentMetadata>
  </subDocuments>
  <subDocuments attachmentId="xx2">
  <DocumentMetadata>
  <DocumentTypeCode>Spreadsheet2</DocumentTypeCode>
  <PackageId>pkg1</PackageId>
  </DocumentMetadata>
  </subDocuments>
  <subDocuments attachmentId="xx2">
 
</ns2:RetsubPack>


Answers (2)