如何在XML文件中获取值的父节点?

时间:2012-12-13 06:17:12

标签: xml vb.net

下面是我的XML文件和函数,用于使用值获取父节点。但我很震惊得到父节点。

当值133传递给函数时,它应该返回“firstnode” 当124传递给函数时,它应该返回“secondnode”

我该怎么做?我使用的是vb.net,但我也可以使用C#。

我的XML文件:

<sample>
    <firstnode>
        <id>133</id>
    </firstnode>
    <secondnode>
        <id>124</id>
    </secondnode>
</sample>

我在vb.net中的功能:

Public Shared Function Get_NodeName_by_ID(ByVal ID As String) As String
    Dim value As String = "" 
    Dim strPath = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings("app_settings").ToString())
    Dim doc As New XmlDocument()
    doc.Load(strPath) 

    Return value
End Function

2 个答案:

答案 0 :(得分:3)

XPath为您提供了根据您的要求操作XML Document的工具。 使用下面的XPath表达式来执行此操作,抱歉我的代码在C#中,因此,您需要将其转换为vb。

XPath表达式:sample / * [id = 133]

C#代码:

//Load FileXML
XmlDocument objFileXML = new XmlDocument();

objFileXML .Load(sFilePath);

//For selecting nodes having given value
XmlNodeList lstNodes = objFileXML .SelectNodes("sample/*[id=133]");

注意:如果要动态放置值,可以放置任何变量。它将在你的vb代码中。 我希望这适合你。

答案 1 :(得分:1)

这个解决方案工作者对我来说。

 Dim strPath = HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings("settings").ToString())
            Dim doc As New XmlDocument()
            doc.Load(strPath)

        Dim ParentNode As XmlNodeList = doc.GetElementsByTagName("id")
        For Each node As XmlNode In ParentNode 
            If (ID.Equals(node.ChildNodes(0).Value)) Then
                value = node.ParentNode.Name.ToString()
            End If 
        Next