C# 如果所有节点名称都未知,则解析XML
我在C# 如果所有节点名称都未知,则解析XML,c#,linq-to-xml,C#,Linq To Xml,我在mainXML中有一些其他元素名称,比如WorkPhone,但并非所有元素都有这些名称。如果我添加这些属性并运行它,它会因此得到NullPointerExceptions 特里尼亚 美国 不是使用元素的值属性,而是转换为字符串。这样,如果XML中不存在元素,它将返回null(与往常一样),如果确实存在,则返回实际值 XDocument loaded = XDocument.Parse(mainXML); var ContactInfo = from Contact in loade
mainXML
中有一些其他元素名称,比如WorkPhone
,但并非所有元素都有这些名称。如果我添加这些属性并运行它,它会因此得到NullPointerException
s
特里尼亚
美国
不是使用元素的值
属性,而是转换为字符串。这样,如果XML中不存在元素,它将返回null
(与往常一样),如果确实存在,则返回实际值
XDocument loaded = XDocument.Parse(mainXML);
var ContactInfo =
from Contact in loaded.Descendants("Contacts")
select new
{
ContactID = Contact.Attribute("Id").Value,
Displayed = Contact.Attribute("Displayed").Value,
AddressList = Contact.Descendants("AddressList"),
CellPhone = Contact.Element("CellPhone").Value,
Citation = Contact.Element("Citation").Value,
DrivingLicense = Contact.Element("DrivingLicense").Value,
Fax = Contact.Element("Fax").Value,
HomePhone = Contact.Element("HomePhone").Value,
};
发布您的xml文件…………我无法发布完整的xml它是非常简单的xml,我还有几个节点,比如,如果我在select new查询中写入所有值,它将很好地向我们显示足够的代码(即C#和xml输入),以允许我们重现错误。非常感谢Jeff。我是XML编码新手。你今天帮我省了很多麻烦。:)
var contactInfos =
from contact in loaded.Descendants("Contacts")
select new
{
ContactID = (string)contact.Attribute("Id"),
Displayed = (string)contact.Attribute("Displayed"),
AddressList = contact.Descendants("AddressList"),
CellPhone = (string)contact.Element("CellPhone"),
Citation = (string)contact.Element("Citation"),
DrivingLicense = (string)contact.Element("DrivingLicense"),
Fax = (string)contact.Element("Fax"),
HomePhone = (string)contact.Element("HomePhone"),
WorkPhone = (string)contact.Element("WorkPhone"),
};