Joe Tyman
Joe Tyman

Reputation: 1417

XML Document Parsing C#

I have a REST web service that creates a XMLDocument I am a bit confused on how access the inner text in FormattedPrice using XMLNode. I can grad offers but that will give me all the inner text.

<Offers>
    <Offer>
       <OfferListing>
          <Price>
            <Amount>1067</Amount>
            <CurrencyCode>USD</CurrencyCode>
            <FormattedPrice>$10.67</FormattedPrice>
          </Price>
       </OfferListing>
    </Offer>
</Offers>

Upvotes: 2

Views: 8606

Answers (6)

dkackman
dkackman

Reputation: 15579

A quick walk-through of XPath will help immensely if you're using the Xml DOM.

This should meet your immediate need:

XmlNode n = doc.DocumentElement.SelectSingleNode("Offer/OfferListing/Price/FormattedPrice");

That will get you the first Offer's Formatted price (and assumes that your Offers node is the root). Other mechanisms exist in XPath that are a bit less brittle and that's where a tutorial would help you.

Upvotes: 5

sexysax
sexysax

Reputation: 1

First off, your XML is invalid....you are missing the starting OfferListing tag.

Here is yet another option to grab the node text.

var xmlString = "<Offers><Offer><OfferListing><Price><Amount>1067</Amount<CurrencyCode>USD</CurrencyCode><FormattedPrice>$10.67</FormattedPrice></Price></OfferListing></Offer></Offers>";

var xDoc = new XmlDocument();
xDoc.LoadXml(xmlString);
var formattedPrice = xDoc.GetElementsByTagName("FormattedPrice")[0].InnerText;

Upvotes: 0

curtisk
curtisk

Reputation: 20175

Load what you want into a XmlNodeList and then pull one explicitly or loop through them...

XmlNodeList pricesList = xmlDoc.GetElementsByTagName("FormattedPrice");
string firstPrice = pricesList[0].InnerText;

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 161002

This should grab the $ amount:

var price = doc.SelectSingleNode(@"//Offer/Price/FormattedPrice");
string priceText = price.InnerText;

Upvotes: 0

agent-j
agent-j

Reputation: 27943

You are probably be best off using XPath.

XmlDocument doc = ...;

XmlNode fPrice;
XmlElement root = doc.DocumentElement;
fPrice= root.SelectSingleNode("/Price/FormattedPrice");

return fPrice.InnerText;

Here's a good example: http://www.codeproject.com/KB/cpp/myXPath.aspx

Upvotes: 4

Petar Ivanov
Petar Ivanov

Reputation: 93090

Use XElement to parse it:

string tmp = @"
<Offers>

<Offer>
 <Price>
   <Amount>1067</Amount>
   <CurrencyCode>USD</CurrencyCode>
   <FormattedPrice>$10.67</FormattedPrice>
 </Price>
 </Offer>
</Offers>";

XElement xml = XElement.Parse(tmp);
string formatedPrice = (string)xml.XPathSelectElement("/Offer/Price/FormattedPrice");

Upvotes: 0

Related Questions