开发者

Accessing child node value with parent reference with LINQ to XML

I am stuck with accessing child node value. Below is the XML structure and the code to create new contact.

<Order xmlns="http://example.com">
    <MiscContact>
        <MiscContact>
            <ContactType>MailingContact</ContactType>
            <Contact>
                &l开发者_StackOverflow社区t;Name>
                    <First>JIM</First>                      
                    <Last>RON</Last>
                    <FullName>RON JIM</FullName>
                </Name>
                <IsValid>false</IsValid>
              </Contact>
        </MiscContact>
    </MiscContact> 
    <ExportForm>
        <Contact>
            <Name>
                <First>JIM</First>                      
                <Last>RON</Last>
                <FullName>RON JIM</FullName>                   
            </Name>                
        <IsValid>false</IsValid>
        </Contact>
    </ExportForm>
</Order>

Code to create new contact only for <MiscContact>:

XNamespace Namespace = "http://online.us.com";
var MiscContact = from mc in xmlDoc.Descendants(Namespace + "Contact") 
                  where mc.Parent.Name.Equals("MiscContact")
                  select new Contact
                  { Name = ob.Element(Namespace + "Name").Value }

Issue i encountered is that even though i have where clause to select only contact whose parent is MiscContact, but contact section both from <MiscContact> and <ExportForm> are getting loaded.

Any idea how to resolve this issue?


Your code appears to be working correctly with the where clause and pulls the Name element from MiscContact -> Contact -> Name. I think your problem is that you're using .Value in the end, which concatenates all these values together:

<Name>
  <First>JIM</First>                      
  <Last>RON</Last>
  <FullName>RON JIM</FullName>
</Name>

The result is "JIMRONRON JIM". If you need the "FullName" then you should use:

mc.Element(Namespace + "Name")
  .Element(Namespace + "FullName").Value

Replace "FullName" with "First" or "Last" as needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜