Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果所有节点名称都未知,则解析XML_C#_Linq To Xml - Fatal编程技术网

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"),
    };