使用XmlDocument获取xml值

时间:2018-07-28 08:56:09

标签: c# xml xmldocument

我想从下面的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>

1 个答案:

答案 0 :(得分:0)

您有一个必须用于获取值的名称空间。这是使用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();
            }
        }
    }
}