Search code examples
xmlvb.netxpathdocument

How to search XML Tags based on a ID using XPathDocument?


Below mentioned is a part of my XML:

<ParentNode>
    <NewCommentID>UniqueID02</NewCommentID>
    <Comment>
        <CommentId>UniqueID01</CommentId> 
        <CommentDesc>Some comments</CommentDesc> 
        <CommentTypeCd>Code1</CommentTypeCd> 
        <CreatedDt>2013-11-29</CreatedDt> 
        <CreatedByUserId>user01</CreatedByUserId> 
        <GivenName>Mitchell</GivenName> 
        <Surname>Johnson</Surname> 
    </Comment>
    <Comment>
        <CommentId>UniqueID02</CommentId> 
        <CommentDesc>Some Comments....</CommentDesc> 
        <CommentTypeCd>Code2</CommentTypeCd> 
        <CreatedDt>2013-11-29</CreatedDt> 
        <CreatedByUserId>user02</CreatedByUserId> 
        <GivenName>Mike</GivenName> 
        <Surname>Jobs</Surname> 
    </Comment>
</ParentNode>

I want to get the details of all the nodes under Comment section, but the which section to select will be decided by Node (NewCommentID). In the above example as the value in 'NewCommentID = UniqueID02', I want to fetch all the tags and their values under Comment section where the CommentID = UniqueID02 using XPathDocument.

Can someone guide how to achieve the same using VB.net?


Solution

  • You can try this way :

    Dim xpathDoc As New XPathDocument("Path_to_xml_file.xml")
    Dim navigator As XPathNavigator
    
    navigator = xpathDoc.CreateNavigator()
    Dim result = navigator.Select("//Comment[./CommentId=../NewCommentID]")