开发者

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.

<Offe开发者_运维技巧rs>
    <Offer>
       <OfferListing>
          <Price>
            <Amount>1067</Amount>
            <CurrencyCode>USD</CurrencyCode>
            <FormattedPrice>$10.67</FormattedPrice>
          </Price>
       </OfferListing>
    </Offer>
</Offers>


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.


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


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


This should grab the $ amount:

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


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;


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜