使用vb.net和xElement获取XML文档中的行数

时间:2014-07-30 15:41:29

标签: xml vb.net numbers line xelement

当我在vb.net上解析它时,我需要检索xml文档的行号和列号; 这是一个例子:

的xml:

<?xml version = "1,0"encoding = "utf-8"?>        <!-- line 1 -->

 <user>                                          <!-- line 2 -->
        <name>dave</name>                        <!-- line 3 -->
        <age>29</age>                            <!-- line 4 -->
        <function>medic</function>               <!-- line 5 --><!-- col 8  -->
 </user>                                         <!-- line 6 -->

VB:

Dim xelement As XElement = xelement.load(xmlDocName) 
'xmlDocName is the path of the document'

Dim nodes = from data in xelement.elements("user")
for each xEle in nodes
        name = xEle.Elements.("name").value.toString
        age  = xEle.Elements.("age").value.toString
        func = xEle.Elements.("function").value.toString

        if func = string.empty then
        'Here is my problem:'
        'I need some thing like that:'
            line = xEle.Elements.("age").lineNumber.toString
            'the variable line should receve the value '5''
             col = xEle.Elements.("age").colNumber.toString
            'the variable col should receve the value '8''

          'But those methods does not exist...'
        end if
next

我需要使用XElement课程的帮助,如果不可能,我将不得不改变它。

1 个答案:

答案 0 :(得分:0)

我找到了获取行号的方法,它正在运行,但我不知道它是否是最佳方式 解决我的问题。此外,我必须测试性能,以便在大文档中使用此代码并处理大量xmls。

vb:

Dim xelement As XElement = xelement.load(xmlDocName,LoadOptions.SetLineInfo) 
'xmlDocName is the path of the document'  
Dim nodes = from data in  xelement.elements("user")
for each xEle in nodes
      name = xEle.Elements.("name").value.toString
      age  = xEle.Elements.("age").value.toString
      func = xEle.Elements.("function").value.toString

      if func = string.empty then
          Dim nodes2 = from data in xelement.elements("user").elements("function")
          Dim info As IXmlLineInfo = nodes2.first
          line = info.LineNumber
      end if
next