我有一个需要解析并加载到c#类中的xml字符串列表。我收到空引用异常,并认为它的“根”原因是在xml中使用的命名空间。我不熟悉ling到xml,所以如果这个解决方案看起来不好,请提供替代方案。XML:XElement.Parse正在抛出异常
这里的解析代码:
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>
这是有道理的,但我仍然得到例外。任何方式我可以更好地获取调试信息,而不是捕获异常? –