簡體   English   中英

使用XmlDocument獲取xml值

[英]Grab xml value using 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>

您必須使用一個名稱空間來獲取值。 這是使用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();
            }
        }
    }
}

暫無
暫無

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

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