如何获取 SOAP 元素值



我有以下 SOAP 响应,我想从 tag 元素中获取值。如何使用 c# 实现此目的?

<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header>
<SessionId xmlns="http://schemas.test.com/Practice/">10ac349210ac3492000000001565976562345</SessionId>
<SequenceId xmlns="http://schemas.test.com/Practice/">9852523457481420</SequenceId>
</S:Header>
<S:Body>
<Response xmlns="http://schemas.test.com/Practice/">
<Attributes>
<getResponseSubscription xmlns="http://schemas.test.com/test/UserProfile/Practice/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID>5643323</ID>
<name>John Brown Jr</name>
<address>New York</address>
</getResponseSubscription>
</Attributes>
</Response>
</S:Body>
</S:Envelope>

我尝试了以下内容,但它返回 null:

var str = XElement.Parse(xml.Response.XmlResponse.ToString()); 
var result = str.Element("Address").Value; 
NormalRoamingValue.Text = result.ToString();

我看到你的代码有几个问题:

  • XML 节点是"地址",但您正在寻找"地址"(大写"A"(。
  • XML 节点是使用命名空间定义的,因此您需要在搜索中使用该命名空间。
  • Element方法查找到当前节点的直接子节点 - 在本例中,将子节点定向到根元素。

请尝试以下代码:

XNamespace ns = "http://schemas.test.com/test/UserProfile/Practice/";
var result = str.Descendants(ns + "address").First();
// If you need a string result, use the .Value property:
var stringResult = result.Value;

请注意,Descendants方法检查当前节点下的任何匹配元素,因此它限于仅查看直接子节点。此外,First调用假定 XML 中只有一个"地址"节点。这些假设可能不适合您,但此代码将为您指明正确的方向。

使用 Xml Linq 尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
string response = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(response);
List<XElement> getResponseSubscription = doc.Descendants().Where(x => x.Name.LocalName == "getResponseSubscription").ToList();
XNamespace ns = getResponseSubscription.FirstOrDefault().GetDefaultNamespace();
var results = getResponseSubscription.Select(x => new
{
id = (string)x.Descendants(ns + "ID").FirstOrDefault(),
name = (string)x.Descendants(ns + "name").FirstOrDefault(),
address = (string)x.Descendants(ns + "address").FirstOrDefault()
}).FirstOrDefault();

}
}
}