user1003054
user1003054

Reputation: 31

Parsing XML if all the node names are not known

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

I have some other element names in the mainXML like WorkPhone which doesn't exist in all elements. If I add these properties and run it, it get NullPointerExceptions because of this.

<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>

Upvotes: 0

Views: 72

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134881

Rather than using the Value property of the elements, cast to a string. That way if an element doesn't exist in your XML, it would return null (like usual) and the actual value if it did exist.

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

Upvotes: 1

Related Questions