如果所有节点名称都未知,则解析XML

时间:2011-10-19 11:53:46

标签: c# linq-to-xml

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

我在mainXML中有一些其他元素名称,如WorkPhone,并不存在于所有元素中。如果我添加这些属性并运行它,则会因此而获得NullPointerException

<Contacts Id="firstcontact" Displayed="False">
    <IsCaller />
    <Role />
    <RelationToRole />
    <PersonInfo>
        <DBA />
        <DateOfBirth />
        <FirstName>TRinya</FirstName>
        <LastName />
        <MiddleName />
    </PersonInfo>
    <AddressList>
        <AddressLine1 />
        <City />
        <Email />
        <EmailPreferred />
        <State />
        <ZipCode />
        <pyCountry>USA</pyCountry>
    </AddressList>
    <Citation />
    <DrivingLicense />
    <Language />
    <InterpreterNeeded />
    <Pedestrian />
    <PersonalInjury>
        <InjuredYesNoUnk />
        <TypeOfInjury />
        <InjuredAffectedArea />
        <InjuryDescription />
    </PersonalInjury>
    <PositionInVehicle />
    <HomePhone />
    <CellPhone />
    <pyWorkPhone />
    <Fax />
    <PrimaryPhone />
    <PrimaryPhoneType />
</Contacts>

1 个答案:

答案 0 :(得分:1)

不是使用元素的Value属性,而是强制转换为字符串。这样,如果XML中不存在某个元素,它将返回null(与通常一样)和实际值(如果它确实存在)。

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