简体   繁体   中英

how to get specific nodes from XML string in C#

I'm trying to get "cust_name" and "code" nodes from a web API XML response below.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cust_list xmlns="http://example.com">
    <cust>
        <cust_id>1234</cust_id>
        <cust_name>abcd</cust_name>
        <cust_type>
            <code>2006</code>
        </cust_type>
    </cust>
</cust_list>

I'm writing the response as string to XMLDocument and trying to read from it. Below is my code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://serviceURI");
request.Method = "GET";
request.ContentType = "Application/XML";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

using (var reader = new StreamReader(response.GetResponseStream()))
{
    string responseValue = reader.ReadToEnd();
    var doc = new XmlDocument();
    doc.LoadXml(responseValue);

    string node = doc.SelectSingleNode("/cust_list/cust/cust_name").InnerText;
    string node2 = doc.SelectSingleNode("/cust_list/cust/cust_type/code").InnerText;
}

I'm trying to target specific nodes but getting "object reference not set to an instance of an object" error. what am i doing wrong here?

XElement xml = XElement.Parse(xmlString);
XNamespace ns = (string)xml.Attribute("xmlns");
var customers = xml.Elements(ns + "cust")
    .Select(c => new
    {
        name = (string)c.Element(ns + "cust_name"),
        code = (int)c.Element(ns + "cust_type")
            .Element(ns + "code")
    });

In this example an XElement is parsed from the input string.

A Namespace is also created using the attribute xmlns . Note how this is used when selecting elements.

All cust elements in the root element are selected and projected into a new anonymous type that currently declares a string name and an int code (you can extend this as needed).

So for example, to get the name of the first customer you could do the following:

string name = customers.First().name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM