Parsing XML from string

70 views Asked by At

I'm sure this is very simple..

I have this as a string:

<OnTheRoadQuote xmlns:i="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://schemas.datacontract.org/2004/07/OTRAPI.Services.Models">
<BasicPrice>15595.8333</BasicPrice>
<CO2>93</CO2>
<Dealer>Audi</Dealer>
<DeliveryCost>524.9900</DeliveryCost>
<DiscountPrice>14348.166636</DiscountPrice>
<DiscountSum>1247.666664</DiscountSum>
<Discounts>
<Discount>
<DiscountApplication>Percentage</DiscountApplication>
<DiscountDescription>Dealer Discount on Vehicle and Options %</DiscountDescription>
<DiscountID>Discount1</DiscountID>
<DiscountType>VehicleAndOptions</DiscountType>
<DiscountValue>8</DiscountValue>
</Discount>
</Discounts>
<OTR>17902.7879632</OTR>
</OnTheRoadQuote>

How do I read the value of the OTR node?

I've got an XmlReader but not sure how to use it.

Thanks

2

There are 2 answers

0
Dan Field On

Using XmlReader, and fixing a typo in your root element (missing space before the second xmlns):

string xml = @"<OnTheRoadQuote xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/OTRAPI.Services.Models"">
  <BasicPrice>15595.8333</BasicPrice>
  <CO2>93</CO2>
  <Dealer>Audi</Dealer>
  <DeliveryCost>524.9900</DeliveryCost>
  <DiscountPrice>14348.166636</DiscountPrice>
  <DiscountSum>1247.666664</DiscountSum>
  <Discounts>
    <Discount>
        <DiscountApplication>Percentage</DiscountApplication>
        <DiscountDescription>Dealer Discount on Vehicle and Options %</DiscountDescription>
        <DiscountID>Discount1</DiscountID>
        <DiscountType>VehicleAndOptions</DiscountType>
        <DiscountValue>8</DiscountValue>
    </Discount>
  </Discounts>
  <OTR>17902.7879632</OTR>
</OnTheRoadQuote>";

string otrValue = "";
using (XmlReader reader = XmlReader.Create(new StringReader(xml))) // use a StringReader to load the XML string into an XmlReader
{
   reader.ReadToFollowing("OTR"); // move the reader to OTR
   reader.ReadStartElement(); // consume the start element
   otrValue = reader.Value; // store the value in the otrValue string.
}

Keep in mind that XmlReader is forward only, meaning that you can't navigate it backwards through the XML data to read, for example, Discounts, once you've pushed it to the OTR node. If you want to do that, you should look into using XmlDocument or (preferably) XDocument. However, if all you need to do is get the OTR value, this should be the most efficient (time and space) way of doing so.

0
William Xifaras On

With less code, you can use LINQ to XML and load an XElement with the xml or a file. There are also other options.

XElement element = XElement.Load(....);
var node = element.Element("OTR");

https://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.load%28v=vs.110%29.aspx