繁体   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