在vb中以XML格式检索值

时间:2014-05-29 16:28:11

标签: xml vb.net parsing

我正在寻找一种更有效的方法,使用VB在以下XML中从@agesex中检索“F”。

以下是我们的XML结构的缩短版本:

    <GridRow XMLVersion="1.0" ColumnNames="Description|Notes|Detail Question|Detail Question Id">
        <Row>


> ...

        </Row>


> ...

        <Row>
            <NodeLevel>0</NodeLevel>
            <RowData>Cancer|@agesex=F;;|Cancer - Female|2320</RowData>
            <RowStyle>|||</RowStyle>
        </Row>
    </Gridrow>

以下是我们的观点。

xmlDoc.LoadXml(topProblemListTemplate.TemplateXml)
            nodeList = xmlDoc.SelectNodes("/GridRow")

            For Each row As XmlNode In nodeList
                For Each item As XmlNode In row.ChildNodes
                    If item.InnerText.Contains("@agesex") Then
                        Dim index As Integer = item.InnerText.IndexOf("@agesex=") + Len("@agesex=")

                        If index > 0 Then
                            Dim value As String = item.InnerText.Substring(index, 1)
                        End If
                    End If
                Next
            Next

1 个答案:

答案 0 :(得分:1)

使用:XmlDocument Class (MSDN)

Imports System.Xml
Imports System.Text.RegularExpressions

Dim d As New XmlDocument
d.Load("file.xml")
' ... in this specific case (or /GridRow/Row/RowData if you want to be specific)
' ... will select all RowData nodes in the document at least 1 level deep.
Dim _rowNodes As XmlNodeList = d.SelectNodes(".//RowData")
For Each _rowNode As XmlNode in _rowNodes
    If New Regex("@agesex=.", RegexOptions.None).Match(s).ToString.endswith("F") Then
        ' ... doSomething
    End If
Next
' ... example only
Dim _rowNodes As XmlNodeList = d.SelectNodes("//GridRow")
For Each _rowNode As XmlNode in _rowNodes
    ' ... iterating over each GridRow
    For Each _childNode As XmlNode in _rowNode
        ' ... iterating over each Row
        For Each _itemNode As XmlNode in _childNode
            ' ... iterating over Each Item in the Row
            Dim a As String = _itemNode.InnerText.Trim
        Next
        ' ... or can just get the node directly
        Dim b As String = _childNode.SelectSingleNode("RowData").InnerText.Trim
        ' ... to specify properties (assuming fictional gender):
        Dim g As String = "female"
        Dim c As XmlNodeList = _childNode.SelectNodes("RowData[@gender='" & g & "']")
        ' ... also as per the documentation, you can match on the value (the data contained in .InnerText property)
        Dim e As String = "myValue"
        Dim f As XmlNodeList = _childNode.SelectNodes("RowData[.='" & e & "']")
    Next
Next

示例:HOW TO: Use the System.Xml.XmlDocument Class to Run XPath Queries in Visual Basic .NET

正如本文档所述,用于查询的lang /表示法是:XPath Examples (MSDN),如果您知道要查找的数据,则支持更具选择性的查询。

同样,XML properties的定义如下:

<myItem name="myName" gender="female">value</myItem>

如果性别属于某个属性,则会更容易,如上例所示,即:

Dim g = "F" : d.SelectNodes(".//RowData[@gender='" & g & "']"); p