【问题标题】:Grab xml value using XmlDocument使用 XmlDocument 获取 xml 值
【发布时间】:2018-07-28 08:56:08
【问题描述】:

我想从以下 XML 示例节点中获取 UPC 值,但当前的 doc.SelectNodes 无法获取该值。我正在使用 XmlDocument 来处理我的 XML。你能修复我的代码以获取 UPC 值吗?我在这里做错了什么?

C#代码:

string responseStr = new StreamReader(responseStream).ReadToEnd();
responseStream.Flush();
responseStream.Close();

XmlDocument doc = new XmlDocument();
doc.LoadXml(responseStr);
if (doc.GetElementsByTagName("Ack").Item(0).InnerText != "Failure")
{
    string UPC = doc.SelectNodes("Item").Item(0).SelectNodes("UPC").Item(0).InnerText;
}

XML 示例:

<?xml version="1.0" encoding="UTF-8"?>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2018-07-28T08:18:10.048Z</Timestamp>
<Ack>Success</Ack>
<Version>1069</Version>
<Build>E1069_CORE_API_18748854_R1</Build>
<Item>
    <ProductListingDetails>
        <ISBN>Not Applicable</ISBN>
        <UPC>853365007036</UPC>
        <EAN>0853365007036</EAN>
        <BrandMPN>
        <Brand>UpCart</Brand>
        <MPN>MPCB-1DX</MPN>
        </BrandMPN>
        <IncludeeBayProductDetails>true</IncludeeBayProductDetails>
    </ProductListingDetails>
</Item>
</GetItemResponse>

【问题讨论】:

标签: c# xml xmldocument


【解决方案1】:

您有一个必须用于获取值的命名空间。这是使用 xml linq 的简单方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            string UPC = (string)doc.Descendants(ns + "UPC").FirstOrDefault();
        }
    }
}

如果你有空值使用这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            var upcs = doc.Descendants(ns + "UPC");
            if (upcs != null)
            {
                string upc = (string)upcs.FirstOrDefault();
            }
        }
    }
}

【讨论】:

  • doc 不包含Root 的定义
  • 您使用的是旧的 XmlDocument。我正在使用新的 msdn 库 XDo​​cument。查看我代码中的标题。
  • 好的,但你会在我的代码中看到我也使用了if 条件。那我怎样才能把它转换成你的 XDoc 版本呢? if(doc.GetElementsByTagName("Ack").Item(0).InnerText != "Failure"){}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2015-05-18
  • 2010-10-30
  • 1970-01-01
  • 2021-09-30
  • 2012-10-20
相关资源
最近更新 更多