浏览XmlNodeList(vb.net)中的节点

时间:2018-05-09 17:59:17

标签: xml vb.net xmlnodelist

我无法在文档中找到如何浏览"通过XmlNodeList中已有的节点。

鉴于此XML:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <tu changedate="20180509T145123Z" creationdate="20180509T145123Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">320920</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello1</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola1</seg>
    </tuv>
  </tu>
  <tu changedate="20180509T145216Z" creationdate="20180509T145216Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">325152</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello2</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola2</seg>
    </tuv>
  </tu>
</tmx>

我正在尝试遍历每个/ tu中的不同节点以将其加载到数据库。应该很简单,但我正在努力学习语法。

到目前为止,我有这个:

Dim tmxfile As String = "d:\Documents\Desktop\myxml.xml"
        Dim xmldoc As New XmlDocument
        xmldoc.Load(tmxfile)

        Dim nodes As XmlNodeList = xmldoc.DocumentElement.SelectNodes("//tu")

        For node = 0 To nodes.Count - 1
            Dim x = nodes.Item(node).SelectNodes("/seg")

            MsgBox(x.ToString)
        Next
    End Sub

我想要实现的是在// tu中显示每个/ seg。代码的第一部分很好,好像我用innerxml或innertext循环遍历节点我看到了XML的实际元素,但我很难在这些节点上获取指定的元素。

任何指导?

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果您使用XDocument代替XmlDocument,则可以使用独特的VB功能 - XML Literals

Sub Main()

    Dim xml =
<?xml version="1.0" encoding="utf-8"?>
<tmx version="1.4">
    <tu changedate="20180509T145123Z" creationdate="20180509T145123Z">
        <prop type="aligned">no</prop>
        <prop type="x-context">320920</prop>
        <tuv xml:lang="en-gb">
            <seg>Hello1</seg>
        </tuv>
        <tuv xml:lang="es">
            <seg>Hola1</seg>
        </tuv>
    </tu>
    <tu changedate="20180509T145216Z" creationdate="20180509T145216Z">
        <prop type="aligned">no</prop>
        <prop type="x-context">325152</prop>
        <tuv xml:lang="en-gb">
            <seg>Hello2</seg>
        </tuv>
        <tuv xml:lang="es">
            <seg>Hola2</seg>
        </tuv>
    </tu>
</tmx>

    xml.AddFirst(New XDocumentType("tmx", "SYSTEM", "tmx14.dtd", ""))

    ' All <tu> elements
    Dim tus = xml.<tmx>.<tu>

    For Each tu In tus
        Dim seg = tu.<tuv>.<seg>
        Console.WriteLine(seg.Value)
    Next

    Console.ReadKey(True)

End Sub