了解xml结构的xml文件类型的最佳方法

时间:2015-12-13 06:33:28

标签: c# xml vb.net

我想阅读一个xml文件,并基于一些xml structures我已经知道识别xml的类型(xml 1, xml 2 or xml 3

例如,我知道3个xml结构:

xml 1

<?xml version="1.0"?>
<OS>
  <Info>
   ...
  </Info>
</OS>

xml 2

<?xml version="1.0" encoding="UTF-8"?>
<SaData Version="2">
  <Cli>
  ...
  </Cli>
</SaData>

xml 3

<?xml version="1.0" encoding="UTF-8"?>
<Init>
     <Danit>
     ...
     </Danit>
</Init>

到目前为止,我有一个类XMLBrandRecognitionNode作为string enum用于xmlTypes列表(我使用列表来完成它,因为xml类型的数量可以增长,现在只有3种类型)

Public Class XMLBrandRecognitionNode
        Private Key As String
        Public Shared ReadOnly xml1 As XMLBrandRecognitionNode = New XMLBrandRecognitionNode("/OS/Info")
        Public Shared ReadOnly xml2 As XMLBrandRecognitionNode = New XMLBrandRecognitionNode("/SaData/Cli")
        Public Shared ReadOnly xml3 As XMLBrandRecognitionNode = New XMLBrandRecognitionNode("/Init/Danit")
        Private Sub New(ByVal key As String)
            Me.Key = key
        End Sub
        Public Overrides Function ToString() As String
            Return Me.Key
        End Function
    End Class

然后我将列表填充为:

Dim recognitionList As New List(Of XMLBrandRecognitionNode)
recognitionList.Add(XMLTypeN.xml1)
recognitionList.Add(XMLTypeN.xml2)
recognitionList.Add(XMLTypeN.xml3)

现在要对文件进行分类(xml1,xml2,xml3

Dim m_xmld As XmlDocument
m_xmld = New XmlDocument()
m_xmld.Load("myXML.xml")

但是我不知道对类型进行分类的最佳方法,我正在考虑 做一个循环,并根据我得到的节点列表返回类型

For Each o As XMLBrandRecognitionNode In recognitionList
   Try
        child_nodes = m_xmld.GetElementsByTagName(o.ToString)
        'maybe a condition or something...

   Catch ex As Exception
         Continue For
   End Try
Next

估算xml文件类型的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

XML Schema Definition,这是描述XML结构的标准方法。为每种XML类型创建一个XSD,然后您可以针对每个XSD测试XML文档,以了解XML符合哪个模式。

但是,对于简单的场景,您可能只想编写自己的简单逻辑来对XML文档进行分类。

这是一种可能的方式。如果True之一识别出XML结构,则该方法将返回xmlType并将patterns设置为正确的类型,否则该方法只返回False

Public Function CheckXmlType(doc As XmlDocument, ByRef xmlType As String) As Boolean
    xmlType = "not recognized"
    'you can change this to dictionary(of enum, string) if you like'
    Dim patterns = New Dictionary(Of String, String)()
    patterns.Add("type1", "/OS/Info")
    patterns.Add("type2", "/SaData/Cli")
    patterns.Add("type3", "/Init/Danit")
    For Each p In patterns
        Dim test = doc.SelectSingleNode(p.Value)
        If test IsNot Nothing
            xmlType = p.Key
            Return True
        End If
    Next

    Return False
End Function

然后你可以这样使用它:

Dim m_xmld As XmlDocument
m_xmld = New XmlDocument()
m_xmld.Load("myXML.xml")

Dim xmlType As String = ""
If m_xmld.CheckXmlType(xmlType)
    'this should print type1/type2/type3 according to the content of myXML.xml'
    Console.WriteLine(xmlType)
Else
    Console.WriteLine("XML type is not recognized")
End If