簡體   English   中英

從字符串解析 XML

[英]Parsing XML from 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>

如何讀取OTR節點的值?

我有一個 XmlReader 但不知道如何使用它。

謝謝

使用 XmlReader,並修復根元素中的拼寫錯誤(第二個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.
}

請記住, XmlReader 是forward only ,這意味着一旦將其推送到OTR節點,您就無法通過 XML 數據向后導航以讀取例如Discounts 如果你想這樣做,你應該考慮使用XmlDocument或(最好) XDocument 但是,如果您只需要獲取 OTR 值,這應該是最有效(時間和空間)的方法。

使用較少的代碼,您可以使用 LINQ to XML 並使用 xml 或文件加載 XElement。 還有其他選擇。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM