从 xml 元素中读取值,在 c# 中标签名称包含冒号 (:)

Read value from xml element which tag name contains colon (:) in c#

我从 webservice 提供的 soapResponse 中提取了 body 数据。但我无法从数据之间和下方包含冒号的标签中提取 body 响应。

XML 示例数据:

<?xml encoding="UTF-8"?> 
    <soapenv:Envelope xmlns:soapenv="http://abc/envelope/"> 
      <soapenv:Header xmlns:view="http://abc/ViewCusReq" /> 
       <soapenv:Body xmlns:view="http://abc/ViewCusReq"> 
           <ns3:Cus_Res xmlns:ns3="http://abc/ViewCusResp"> 
                <ns3:ReqID>123</ns3:ReqID> 
                <ns3:FName>ab</ns3:FName> 
           </ns3:Cus_Res> 
          <ns3:Cus_Res xmlns:ns3="http://test.com/ViewCusResp"> 
                <ns3:ReqID>123</ns3:ReqID> 
                <ns3:FName>ab</ns3:FName> 
          </ns3:Cus_Res> 
        </soapenv:Body>
      </soapenv:Header>
    </soapenv:Envelope>

在 c# 代码下面使用,用于获取 ReqIDAbhiFNameav 的值列表,但它 returns empty/null.

var responseEle = from lst in xDoc.Descendants((XNamespace)"http://test.com/ViewCusResp" + "ReqID") select lst;

我知道,我查询的格式有误,谁能帮我解决这个问题。提前谢谢你。

如果不知道您的 xml 是否只是一个基本示例,或者它是否(一旦更正)是您在生产中使用的真实示例,则很难做出回答。 会有很多 Cus_Res 个节点吗?

要回答您的确切问题,请参阅下面的代码,该代码 select 是节点并获取值。但是,如果您的生产 xml 更复杂,那么您需要做更多的工作来循环 Cus_Res 的集合,例如。

string xml = @"<?xml version=""1.0"" encoding=""UTF - 8""?>
<ns3:Cus_Res xmlns:ns3=""http://test.com/customerResponse"">
    <ns3:ReqID> 123456789 </ns3:ReqID>
    <ns3:FName> Abhinav </ns3:FName>
</ns3:Cus_Res>";

XNamespace xn = "http://test.com/customerResponse";

var xDoc = XDocument.Parse(xml);
var reqid  = xDoc.Descendants(xn + "ReqID").First();
var fname = xDoc.Descendants(xn + "FName").First();

Console.WriteLine(reqid.Value);
Console.WriteLine(fname.Value);

Update

如果您在根元素中有许多 Cus_Res 节点,您将 select 所有 Cus_Res 节点然后遍历它们,访问它的直接子节点。

同样,不需要对您的 xml 做太多修改就可以打破这一点,您还应该进行我没有演示的空值检查:

string xml = @"<?xml version=""1.0"" encoding=""UTF - 8""?>
<root>
    <ns3:Cus_Res xmlns:ns3=""http://test.com/customerResponse"">
        <ns3:ReqID> 123456789 </ns3:ReqID>
        <ns3:FName> Abhinav </ns3:FName>
    </ns3:Cus_Res>
    <ns3:Cus_Res xmlns:ns3=""http://test.com/customerResponse"">
        <ns3:ReqID> 3456 </ns3:ReqID>
        <ns3:FName> Wayne </ns3:FName>
    </ns3:Cus_Res>
    <ns3:Cus_Res xmlns:ns3=""http://test.com/customerResponse"">
        <ns3:ReqID> 78952</ns3:ReqID>
        <ns3:FName>Garth</ns3:FName>
    </ns3:Cus_Res>
</root>";

XNamespace xn = "http://test.com/customerResponse";

var xDoc = XDocument.Parse(xml);
var CurResList = xDoc.Descendants(xn + "Cus_Res");

foreach (XElement element in CurResList)
{
    Console.WriteLine(element.Element(xn + "ReqID").Value);
    Console.WriteLine(element.Element(xn + "FName").Value);
}