简体   繁体   English

在 C# 中解析 XML 响应

[英]Parse XML response in C#

I got an XML response as:我得到了 XML 响应:

<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns="site.com/api" xmlns:xsi="site.org/2001/XMLSchema-instance" xsi:schemaLocation="site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd">
    <credentials token="xxxxxx-xxxxxx-xxxxxx">
        <site id="xxxxxx-xxxxxx-xxxxxx" contentUrl="sitename"/>
        <user id="xxxxxx-xxxxxx-xxxxxx"/>
    </credentials>
</tsResponse>

How can I parse this response to get the token value inside credentials?如何解析此响应以获取凭据中的令牌值?

By using LINQ to XML.通过使用 LINQ 到 XML。

c# c#

void Main()
{
    XDocument xdoc = XDocument.Parse(@"<tsResponse xmlns='site.com/api' xmlns:xsi='site.org/2001/XMLSchema-instance' xsi:schemaLocation='site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd'>
            <credentials token='xxxxxx-xxxxxx-xxxxxx'>
                <site id='xxxxxx-xxxxxx-xxxxxx' contentUrl='sitename'/>
                <user id='xxxxxx-xxxxxx-xxxxxx'/>
            </credentials>
        </tsResponse>");

    XNamespace ns1 = xdoc.Root.GetDefaultNamespace();

    string token = xdoc.Descendants(ns1 + "credentials")
        .FirstOrDefault()?.Attribute("token").Value;

    Console.WriteLine("token = {0}", token);
}

Output Output

token = xxxxxx-xxxxxx-xxxxxx

If you put the XML string that you get into the variable xmlToParse, you can do:如果您将获得的 XML 字符串放入变量 xmlToParse,您可以执行以下操作:

TsResponse result = _xmlParser.Deserialize<TsResponse>(xmlToParse);

Where _xmlParser is an instance of the class:其中_xmlParser是 class 的一个实例:

using System.Xml.Serialization;

namespace yourNameSpace
{
    public class XmlParser
    {
        public T Deserialize<T>(string input) where T : class
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return (T)ser.Deserialize(sr);
            }
        }
    }
}

You also need to model the whole XML object as a class in C# (XmlObjects.Credentials in my example) using the for example the page https://json2csharp.com/code-converters/xml-to-csharp which gives you: You also need to model the whole XML object as a class in C# (XmlObjects.Credentials in my example) using the for example the page https://json2csharp.com/code-converters/xml-to-csharp which gives you:

// using System.Xml.Serialization;
// XmlSerializer serializer = new XmlSerializer(typeof(TsResponse));
// using (StringReader reader = new StringReader(xml))
// {
//    var test = (TsResponse)serializer.Deserialize(reader);
// }

[XmlRoot(ElementName="site")]
public class Site { 

    [XmlAttribute(AttributeName="id")] 
    public string Id { get; set; } 

    [XmlAttribute(AttributeName="contentUrl")] 
    public string ContentUrl { get; set; } 
}

[XmlRoot(ElementName="user")]
public class User { 

    [XmlAttribute(AttributeName="id")] 
    public string Id { get; set; } 
}

[XmlRoot(ElementName="credentials")]
public class Credentials { 

    [XmlElement(ElementName="site")] 
    public Site Site { get; set; } 

    [XmlElement(ElementName="user")] 
    public User User { get; set; } 

    [XmlAttribute(AttributeName="token")] 
    public string Token { get; set; } 
}

[XmlRoot(ElementName="tsResponse")]
public class TsResponse { 

    [XmlElement(ElementName="credentials")] 
    public Credentials Credentials { get; set; } 

    [XmlAttribute(AttributeName="xmlns")] 
    public string Xmlns { get; set; } 

    [XmlAttribute(AttributeName="xsi")] 
    public string Xsi { get; set; } 

    [XmlAttribute(AttributeName="schemaLocation")] 
    public string SchemaLocation { get; set; } 
}

, then you can go with ,那么您可以使用 go

result.Credentials.Token

I think that the simplest way is to use LINQ to XML's XDocument :我认为最简单的方法是将 LINQ 用于 XML 的XDocument

using System.Xml;
using System.Xml.Linq;

/* ... */

var xml = @"<?xml version='1.0' encoding='UTF-8'?>
<tsResponse xmlns=""site.com/api"" xmlns:xsi=""site.org/2001/XMLSchema-instance"" xsi:schemaLocation=""site.com/api help.site.com/samples/en-us/rest_api/ts-api_3_4.xsd"">
    <credentials token=""xxxxxx-xxxxxx-xxxxxx"">
        <site id=""xxxxxx-xxxxxx-xxxxxx"" contentUrl=""sitename""/>
        <user id=""xxxxxx-xxxxxx-xxxxxx""/>
    </credentials>
</tsResponse>";

var xmlns = XNamespace.Get("site.com/api");
var token = XDocument.Parse(xml)
                     .Element(xmlns + "tsResponse")?
                     .Element(xmlns + "credentials")?
                     .Attribute("token")?
                     .Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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