分别解析XML文件

时间:2018-07-13 09:24:32

标签: xml vb.net

我需要为xml中的每个值向数据表添加行:

<G_3>
 <UPP_ID>3381602200003739</UPP_ID>
</G_3>
    <LIST_G_1>
             <G_1>
              <BROJ>375383321</BROJ>
              <OPERR>11.07.18</OPERR>
              <KOME>22uzu</KOME>
              <TABTEXT>rbnrn</TABTEXT>
              <NAME>Ban</NAME>
              <TASK>6000</TASK>
              <B_TASK>0</B_TASK>
              <FLAG>1</FLAG>
              <ELGE_A>1</ELGE_A>
              <ELGE_B>12000</ELGE_B>
              <ELGE_C>0</ELGE_C>
              <ELGE_D>-134675.56</ELGE_D>
              <ELGE_0>338250220001727</ELGE_0>
            </G_1>
            <G_1>
              <BROJ>375383568</BROJ>
              <OPERR>11.07.18</OPERR>
              <KOME>3383202200001622</KOME>
              <TABTEXT> PL. RN.</TABTEXT>
              <NAME>ban43</NAME>
              <TASK>6000</TASK>
              <B_TASK>0</B_TASK>
              <FLAG>1</FLAG>
              <ELGE_A>1</ELGE_A>
              <ELGE_B>18000</ELGE_B>
              <ELGE_C>0</ELGE_C>
              <ELGE_D>-140675.56</ELGE_D>
              <ELGE_0>3383202200001622</ELGE_0>
            </G_1>

</LIST_G_1>

我将如何为每个循环实现A,以从此xml文件获取值。 这是从此xml中的单个节点返回值的代码的一部分:

 Dim doc As New System.Xml.XmlDocument
        doc.Load(textBox.Text)
        Dim UPP_IDi= doc.GetElementsByTagName("UPP_ID")
        For Each item As System.Xml.XmlElement In UPP_IDi
            UPP_ID.Text = item.InnerText
        Next

我想要在控制台/列表框中显示以下内容:

Broj:375383321
OPERR:11.07.18
KOME:22uzu
...
Broj:375383568
OPERR:11.07.18
KOME:3383202200001622

1 个答案:

答案 0 :(得分:1)

使用Xml Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication53
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            foreach (XElement g_1 in doc.Descendants("G_1"))
            {
                string leader = "";

                foreach (XElement element in g_1.Elements())
                {
                    string output = string.Format("{0}{1}:{2}", leader, element.Name.LocalName, (string)element);
                    Console.WriteLine(output);

                    if (leader.Length == 0) leader = "     ";
                }
            }
            Console.ReadLine();
        }
    }
}