Read XML, different number of nodes

萝らか妹 提交于 2020-04-30 07:20:43

问题


When I am reading an XML file in VB.NET (ASMX webservice), on some occasion, some node may be missing. My code is the following:

nodetype = node("type").InnerText
nodetime = node("time").InnerText
nodefileName = node("fileName").InnerText

And I've thought about this condition to see if the node exists or not. If it does not exist it returns a string with 0.

If node("fileName")Is Nothing Then
  nodefileName = "0"
Else
  nodefileName = nodefileName = node("fileName").InnerText.
End If

Instead of having to do the check for all nodes individually ... how could you do the check for all at once and if it doesn't exist in the XML file put 0 in the corresponding variable? Thanks 1000!

EDIT: XML sample, XML does not always have all nodes.

<?xml version="1.0" encoding="UTF-8"?>
<eventLog>
    <event>
        <type>access1</type>
        <fileName>file.xml</fileName>
        <time>2020-04-25</time>
        <baseExtraData>
            <sample>Bone</sample>
            <age>65</age>
        </baseExtraData>
    </event>
    <event>
        <type>access2</type>
        <fileName>file2.xml</fileName>
        <time>2020-04-24</time>
        <baseExtraData>
            <sample>Malow</sample>
            <age>11</age>
        </baseExtraData>
    </event>
</eventLog>

回答1:


Use Xml Linq :

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

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

            var events = doc.Descendants("event").Select(x => new {
                type = (string)x.Element("type"),
                filename = (string)x.Element("fileName"),
                time = (DateTime)x.Element("time")
            }).ToList();
        }
    }
}



回答2:


Well, here's a solution with one helper function. Added a button "BtnImport" on a form and a textbox named "TxtXML" which holds the path of your xml file:

Imports System.IO
Imports System.Text
Imports System.Xml

Private Function GetNodeText(ByVal Dom As XmlDocument, ByVal Path As String) As String
    Dim Node As XmlNode = Dom.SelectSingleNode(Path)

    If Node Is Nothing Then Return vbNullString
    Return Node.InnerText
End Function

Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
    Dim DOC As New XmlDocument
    Dim SB As New StringBuilder
    Dim Line(4) As String

    SB.Append("type;fileName;time;sample;age")
    SB.Append(vbCrLf)

    DOC.Load(TxtXML.Text)

    Dim Counter As Integer = 1
    Dim EventPath = String.Format("/descendant::event[{0}]", Counter)
    Do Until DOC.SelectSingleNode(EventPath) Is Nothing
        Line(0) = GetNodeText(DOC, EventPath & "/type")
        Line(1) = GetNodeText(DOC, EventPath & "/fileName")
        Line(2) = GetNodeText(DOC, EventPath & "/time")
        Line(3) = GetNodeText(DOC, EventPath & "/baseExtraData/sample")
        Line(4) = GetNodeText(DOC, EventPath & "/baseExtraData/age")

        SB.Append(Join(Line, ";"))
        SB.Append(vbCrLf)

        Counter += 1
        EventPath = String.Format("/descendant::event[{0}]", Counter)
    Loop

    Dim FS As New FileStream(TESTFOLDER & "\Test.csv", FileMode.Create)
    Dim SW As New StreamWriter(FS)

    SW.Write(SB.ToString)
    SW.Close()
End Sub


来源:https://stackoverflow.com/questions/61432556/read-xml-different-number-of-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!