我有一个xml字符串列表,需要解析这些字符串并将其加载到c#类中。我得到了空引用异常,并认为它的“根”原因是xml中使用的命名空间。我对xml不是很熟悉,所以如果这个解决方案看起来很糟糕,请提供替代方案。
下面是解析代码:
XNamespace ns = "http://www.example.com/schema/msc/message";
XNamespace ns2 = "http://www.example.com/schema/msc/referral";
// data is List<string>
Parallel.ForEach(data, item =>
{
   var root = XElement.Parse(item);
   var dto = new DTO
       {
         RoutingCode = (string)root.Element("Message")
               .Element(ns + "Params")
               .Element(ns + "Events")
               .Attribute("Code")
         User = new UserDTO
                    {
                     AccountName = (string)root.Element("Message")
                                  .Element("Params")
                                  .Element("Events")
                                  .Element("ref:User")
                                  .Element("Name")
                    }
       };
     list.Add(dto);
});下面是一个示例xml元素(减小了可读性)
<Message xmlns="http://www.example.com/schema/msc/message">
  <Params> 
    <Events xmlns="http://www.example.com/schema/msc/referral" Code="AC">
      <ref:User xmlns:ref="http://www.example.com/schema/msc/referral" Name="asdf"/>
    </Events>
  </Parama>
</Message>发布于 2015-11-10 21:07:32
尝试将命名空间链接到XElement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string item =
                "<Message xmlns=\"http://www.example.com/schema/msc/message\">" +
                  "<Params>" +
                    "<Events xmlns=\"http://www.example.com/schema/msc/referral\" Code=\"AC\">" +
                      "<ref:User xmlns:ref=\"http://www.example.com/schema/msc/referral\" Name=\"asdf\"/>" +
                    "</Events>" +
                  "</Params>" +
                "</Message>";
            XElement root = XElement.Parse(item);
            XNamespace ns1 = root.Name.Namespace;
            XNamespace ns2 = root.Descendants().Where(x => x.Name.LocalName == "Events").FirstOrDefault().Name.Namespace;
        }
    }
}
https://stackoverflow.com/questions/33637284
复制相似问题