使用c#读取具有嵌套命名空间的XML

时间:2017-01-08 19:14:19

标签: c# xml xnamespace

我正在尝试使用C#从此XML中提取以下值。

消息 - inntertext
成功 ="真" - 只是" true"位
状态 ="发行日期" - 只是"已发布"位

命名空间显然是这里的问题 - 但我无法做到正确。 有人可以提供解析此文件的示例吗?

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <tns:executeCreateLoanIncreaseResponse xmlns:tns="http://api.ws.liq.pisys.com/">
      <CreateLoanIncreaseResponse success="true">
        <OutstandingTransactionAsReturnValue version="1.0" alias="LIBRLC" status="Released" id="5CJB6GS"></OutstandingTransactionAsReturnValue>
        <Messages>
          <Message>CreateLoanIncrease&gt;&gt;Effective date current business date (08-Sep-2016).</Message>
          <Message>CreateLoanIncrease&gt;&gt;Intent Notices have not been generated.</Message>
          <Message>CreateLoanIncrease&gt;&gt;You are about to release this increase.</Message>
        </Messages>
      </CreateLoanIncreaseResponse>
    </tns:executeCreateLoanIncreaseResponse>
  </soapenv:Body>
</soapenv:Envelope>

2 个答案:

答案 0 :(得分:1)

试试xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement messages = doc.Descendants().Where(x => x.Name.LocalName == "Messages").FirstOrDefault();
            XNamespace ns = messages.GetDefaultNamespace();

            List<string> strMessages = messages.Elements(ns + "Message").Select(x => (string)x).ToList();
        }
    }
}

答案 1 :(得分:1)

您可以使用Linq2Xml和XPath

var xDoc = XDocument.Load(filename);

var success = (bool)xDoc.XPathSelectElement("//CreateLoanIncreaseResponse").Attribute("success");
var status = (string)xDoc.XPathSelectElement("//OutstandingTransactionAsReturnValue").Attribute("status");
var messages = xDoc.XPathSelectElements("//Message").Select(x => (string)x.Value).ToList();