【问题标题】:Parsing XML from string从字符串解析 XML
【发布时间】:2015-06-09 14:36:41
【问题描述】:

我相信这很简单..

我有这个字符串:

<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,但不知道如何使用它。

谢谢

【问题讨论】:

  • C# - Reading data from XML 的可能重复项
  • 你为什么没有用谷歌搜索这个?关于如何在 .NET 中从 XML 读取数据的文章数不胜数
  • 公平地说,相关问题集中在使用XmlDocument和/或XDocument。他特别问如何将字符串加载到XmlReader

标签: c# xmlreader


【解决方案1】:

使用 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 只能向前,这意味着一旦将其推送到OTR 节点。如果你想这样做,你应该考虑使用XmlDocument 或(最好)XDocument。但是,如果您只需要获取 OTR 值,这应该是最有效的(时间和空间)方式。

【讨论】:

    【解决方案2】:

    使用更少的代码,您可以使用 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

    【讨论】:

      猜你喜欢
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多