遍历每个xml节点并将节点和值附加到字符串

时间:2013-05-21 05:37:14

标签: vb.net xml-parsing

我有以下xml格式,实际上是谷歌地图的kml文件..

        <kml xmlns="http://www.opengis.net/kml/2.2">
          <Document>
            <Name>TestDoc</Name>
            <Style id="Style1">
              <PolyStyle>
                <fill>0</fill>
              </PolyStyle>
            </Style>
            <Folder>
              <Name>Folder1</Name>
              <Placemark>
                <Name>Placemark1Folder1</Name>
                <LookAt>
                  <longitude>-122.0839597145766</longitude>
                  <latitude>37.42222904525232</latitude>
                </LookAt>
              </Placemark>
              <Placemark>
                <Name>Placemark2Folder1</Name>
                <LookAt>
                  <longitude>-101.083959</longitude>
                  <latitude>26.422</latitude>
                </LookAt>
              </Placemark>
            </Folder>
            <Folder>
              <Name>Folder2</Name>
              <Placemark>
                <Name>Placemark1Folder2</Name>
                <LookAt>
                  <longitude>-96.566556</longitude>
                  <latitude>14.422</latitude>
                </LookAt>
              </Placemark>
            </Folder>
          </Document>
        </kml>

我想将xml连接到字符串变量,直到找到<Folder> node

因此输出字符串将是:

""<kml xmlns="http://www.opengis.net/kml/2.2"><Document><Name>TestDoc</Name><Style id="Style1"><PolyStyle><fill>0</fill></PolyStyle> </Style>"

我是xml ..Plz帮助的新手

1 个答案:

答案 0 :(得分:3)

好的,我明白了......这是我的解决方案

Public Sub ConcatXmlToString()
        Dim xmldoc As XmlDocument = New XmlDocument()
        '================================
        'Hard Coded
        '================================
        Dim ConcatString As String = "<?xml version=" & Chr(34) & "1.0" & Chr(34) & "encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?><kml xmlns=" & Chr(34) & "http://www.opengis.net/kml/2.2" & Chr(34) & ">"

        xmldoc.Load("E:\A01c.kml")
        Dim DocumentNodeList As XmlNodeList = xmldoc.GetElementsByTagName("Document")
        For Each DocumentNode As XmlNode In DocumentNodeList
            'xmldoc.ParentNode.ParentNode.RemoveChild(childnode)
            Dim ChildNodeList As XmlNodeList = DocumentNode.ChildNodes
            For Each ChildNode As XmlNode In ChildNodeList
                If ChildNode.Name <> "Folder" Then
                    ConcatString = ConcatString & ChildNode.OuterXml.Replace("xmlns=""http://www.opengis.net/kml/2.2""", "")
                End If
            Next
        Next

        ConcatString = ConcatString & "</Document></kml>"

        Dim str As String = xmldoc.InnerText

    End Sub