You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android中解析XML响应后如何获取指定值?

Parsing SOAP XML Response in Xamarin Android

Hey there! Parsing SOAP XML responses in Xamarin Android is totally manageable—two go-to approaches work really well here: LINQ to XML (great for quick, targeted extractions) and XmlSerializer (perfect if you want to map the XML to strongly-typed C# classes). Let’s walk through both using your sample SOAP envelope.

First, let’s clarify the full structure of your XML (since your snippet was truncated):

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <IsActive xmlns="http://CTRMService/CTRM">true</IsActive>
  </s:Header>
  <s:Body>
    <GetAllPersonResponse xmlns="http://CTRMService/CTRM">
      <GetAllPersonResult xmlns:a="http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <!-- Contains your list of Person DTO objects -->
      </GetAllPersonResult>
    </GetAllPersonResponse>
  </s:Body>
</s:Envelope>

Method 1: Using LINQ to XML (XDocument)

This is ideal if you only need to pull specific values without building full data models. The key here is properly handling XML namespaces—they’re easy to overlook but critical for accurate parsing.

First, add the required using statement:

using System.Xml.Linq;

Then parse and extract data from your XML string:

// Assume xmlResponse is your raw XML from the network request
XDocument doc = XDocument.Parse(xmlResponse);

// Define all namespaces used in the SOAP envelope
XNamespace soapNs = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ctrmNs = "http://CTRMService/CTRM";
XNamespace dtoNs = "http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO";

// Extract the IsActive value from the header
bool isActive = bool.Parse(
    doc.Descendants(soapNs + "Header")
       .Elements(ctrmNs + "IsActive")
       .FirstOrDefault()?.Value ?? "false"
);

// Extract person data (adjust element names to match your actual DTO structure)
var personList = doc.Descendants(ctrmNs + "GetAllPersonResult")
                    .Elements(dtoNs + "Person")
                    .Select(p => new 
                    {
                        Id = int.Parse(p.Element(dtoNs + "Id")?.Value ?? "0"),
                        FullName = p.Element(dtoNs + "FullName")?.Value
                        // Add other properties as needed
                    })
                    .ToList();

Method 2: Using XmlSerializer with Strongly-Typed Classes

If you want to work with the XML data as structured C# objects (which makes long-term data handling cleaner), create classes that mirror the XML structure—including matching namespaces.

First, define your data model classes:

using System.Xml.Serialization;
using System.Collections.Generic;

// Top-level SOAP envelope
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class SoapEnvelope
{
    [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public SoapHeader Header { get; set; }

    [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public SoapBody Body { get; set; }
}

// SOAP header content
public class SoapHeader
{
    [XmlElement(ElementName = "IsActive", Namespace = "http://CTRMService/CTRM")]
    public bool IsActive { get; set; }
}

// SOAP body content
public class SoapBody
{
    [XmlElement(ElementName = "GetAllPersonResponse", Namespace = "http://CTRMService/CTRM")]
    public GetAllPersonResponse GetAllPersonResponse { get; set; }
}

// Wrapper for the person result list
public class GetAllPersonResponse
{
    [XmlElement(ElementName = "GetAllPersonResult", Namespace = "http://CTRMService/CTRM")]
    public GetAllPersonResult GetAllPersonResult { get; set; }
}

// Container for your Person DTOs
[XmlRoot(ElementName = "GetAllPersonResult", Namespace = "http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO")]
public class GetAllPersonResult
{
    [XmlElement(ElementName = "Person", Namespace = "http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO")]
    public List<Person> Persons { get; set; }
}

// Person DTO (adjust properties to match your actual XML data)
public class Person
{
    [XmlElement(ElementName = "Id", Namespace = "http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO")]
    public int Id { get; set; }

    [XmlElement(ElementName = "FullName", Namespace = "http://schemas.datacontract.org/2004/07/DTOModelLayer.DTO")]
    public string FullName { get; set; }

    // Add other properties (email, age, etc.) as needed
}

Then use XmlSerializer to deserialize the XML into your objects:

using System.Xml.Serialization;
using System.IO;

// Deserialize the raw XML string
XmlSerializer serializer = new XmlSerializer(typeof(SoapEnvelope));
using (StringReader reader = new StringReader(xmlResponse))
{
    SoapEnvelope envelope = (SoapEnvelope)serializer.Deserialize(reader);
    
    // Access your data easily
    bool isServiceActive = envelope.Header.IsActive;
    List<Person> persons = envelope.Body.GetAllPersonResponse.GetAllPersonResult.Persons;
    
    // Do something with the data!
}

Quick Tips to Avoid Headaches:

  • Always handle null values (use ?. or null coalescing operators) to prevent crashes if elements are missing from the XML.
  • If your XML has optional elements, add [XmlElement(IsNullable = true)] to the corresponding class property.
  • For large XML responses, LINQ to XML is more memory-efficient, but XmlSerializer is cleaner for working with structured data long-term.

内容的提问来源于stack exchange,提问作者K. Ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:14:40