在VB .Net中解析XML

时间:2013-08-23 10:57:06

标签: xml vb.net

我正在尝试从另一个应用程序生成的XML文件中提取一些信息,为了清晰起见,这是一个简洁的缩减版本。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--IE2C Current Input-->
<RSLogix5000Content SchemaRevision="1.0" SoftwareRevision="19.01" >
<Controller Use="Context" Name="MAIN">
<AddOnInstructionDefinitions Use="Context">
<EncodedData EncryptionConfig="2">
<Description>
<![CDATA[IE2C Current Input]]>
</Description>
<RevisionNote>
<![CDATA[Initial Revision]]>
</RevisionNote>
zNti6YvCK0McoTr4NZK1iyGdEAkM0sxvRC35nnfg/Gd6x+f1lAbsW0PwA4f9TfqHs3MmOQ9OhS9...</EncodedData>
</AddOnInstructionDefinitions>
</Controller>
</RSLogix5000Content>

我可以使用以下代码成功返回EncryptionConfig值(2):

Dim xml As XPathDocument = New XPathDocument(filepath)
xmlNav = xml.CreateNavigator()
xmlNI = xmlNav.Select("//EncodedData")
While (xmlNI.MoveNext())
    If IsNumeric(xmlNI.Current.GetAttribute("EncryptionConfig", "")) Then
        encryptionconfig = xmlNI.Current.GetAttribute("EncryptionConfig", "")
    Else
        encryptionconfig = 0
    End If
End While
xmlNI = Nothing
xmlNav = Nothing
xml = Nothing

问题是我还需要返回'zNti6YvCK0McoTr4NZK1iyGdEAkM0 ...'值。到目前为止我尝试过的所有内容都会返回它以及我不想要的Description和RevisionNote值。

更新

这是允许未编码文件和一些不包含EncryptionConfig属性的文件版本的最终代码:

Dim b64text As String = ""
Dim encryptionconfig As Integer = 0
Dim xml As XElement = XElement.Load(filepath)
Dim node = xml.Descendants("EncodedData")(0)
If node IsNot Nothing Then
    b64text = node.Nodes().OfType(Of XText)().First().Value.Trim()
    If node.Attribute("EncryptionConfig") IsNot Nothing Then
        encryptionconfig = node.Attribute("EncryptionConfig").Value
    End If
Else
    Label6.ForeColor = Color.Red
    Label6.Text = "File is not encoded"
End If
node = Nothing
xml = Nothing

1 个答案:

答案 0 :(得分:1)

您必须检查<EncodedData>中所有节点的类型以获取文本。一种简单的方法是使用linq2xml,OfType方法和XText类型:

示例:

Dim xml = <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <!--IE2C Current Input-->
            <RSLogix5000Content SchemaRevision="1.0" SoftwareRevision="19.01" >
            <Controller Use="Context" Name="MAIN">
            <AddOnInstructionDefinitions Use="Context">
            <EncodedData EncryptionConfig="2">
            <Description>
            <![CDATA[IE2C Current Input]]>
            </Description>
            <RevisionNote>
            <![CDATA[Initial Revision]]>
            </RevisionNote>
            zNti6YvCK0McoTr4NZK1iyGdEAkM0sxvRC35nnfg/Gd6x+f1lAbsW0PwA4f9TfqHs3MmOQ9OhS9...</EncodedData>
            </AddOnInstructionDefinitions>
            </Controller>
            </RSLogix5000Content>

Dim node = xml.Descendants("EncodedData")(0)
Dim data = node.Nodes().OfType(Of XText)().First().Value.Trim() ' is zNti6YvCK0McoTr4NZK1iyGdEAkM0sxvRC35nnfg/Gd6x+f1lAbsW0PwA4f9TfqHs3MmOQ9OhS9... '
Dim config = node.Attribute("EncryptionConfig").Value ' is 2 '