【已解决】如何获知XML文件中有多少个节点并取得对应的值?
本帖最后由 xowen 于 2021-11-9 20:30 编辑例如,下面是一个XML文件,在不知道XML中的具体内容时,如何获知XML中有多少个有效的节点呢,并且获知XML的节点树结构?即,我要获得每个节点的值,并要知道节点的等级关系。高手快出现吧!!!
<?xml version="1.0" encoding="UTF-8"?>
<test id="100" name="tester01">
<node>test01</node>
<steps>
<step id="1">xxxxxx</step>
<step id="2">yyyyyy</step>
</steps>
</test> 帮助文档里有现成的 html 标签的 正则例子
StringRegExp
;示例 1, 返回匹配项目的数组.并使用偏移量
$nOffset = 1
While 1
$array = StringRegExp('<test>a</test> <test>b</test> <test>c</Test>', '<(?i)test>(.*?)</(?i)test>', 1, $nOffset)
If @error = 0 Then
$nOffset = @extended
Else
ExitLoop
EndIf
for $i = 0 to UBound($array) - 1
msgbox(0, "正则测试 标志值 1 - " & $i, $array[$i])
Next
WEnd
;示例 2, 返回包括完整匹配的数组.(Perl/ PHP 样式).
$array = StringRegExp('<test>a</test> <test>b</test> <test>c</Test>', '<(?i)test>(.*?)</(?i)test>', 2)
for $i = 0 to UBound($array) - 1
msgbox(0, "正则测试 标志值 2 - " & $i, $array[$i])
Next
;示例 3, 返回全局匹配的数组.
$array = StringRegExp('<test>a</test> <test>b</test> <test>c</Test>', '<(?i)test>(.*?)</(?i)test>', 3)
for $i = 0 to UBound($array) - 1
msgbox(0, "正则测试 标志值 3 - " & $i, $array[$i])
Next
;示例 4, 返回包括完整匹配(Perl/ PHP 样式)和全局匹配的数组.
$array = StringRegExp('F1oF2oF3o', '(F.o)*?', 4)
for $i = 0 to UBound($array) - 1
$match = $array[$i]
for $j = 0 to UBound($match) - 1
msgbox(0, "正则测试 标志值 4 - " & $i & ',' & $j, $match[$j])
Next
Next
正则我也不懂
<step id="1">xxxxxx</step>
关键 是把这个 标签 写成正则
等待高手出现 回复 2# veket_linux
关键是事先不知道XML文件中有哪些节点,例子中的节点可能会因环境不同而多出其他节点,也能少节点,因此使用正则表达式就不太好把握了。 不懂
路过帮顶 xmldom里好像有这个 期待高手。。。。。。。。 如果没有相同的node,倒是能够获得每个节点的值,及节点的等级关系。有相同的node,难搞。 XML方面的还要学习啊要用到正则,那就回去看看,因为这段时间要弄这方面的 苦想几天,终获一法。以下代码,针对任意XML文件,能遍历XML中的所有元素(节点),并获所含的文本内容,最后给出所有元素(节点)的路径。#include <Array.au3>
#include <_MSXML.au3>
Dim $oXMLDoc, $strXPath, $sPath, $Element, $n = 0
_MSXML_InitInstance($oXMLDoc)
If @error Then
MsgBox(0, "Error", "Failed to create instance")
Exit
EndIf
_MSXML_FileOpen($oXMLDoc, @ScriptDir & "\test.xml")
If @error Then
MsgBox(0, "Error", _MSXML_Error())
Else
$Element = "/"
While 1
$n = $n + 1
If $n - 1 > UBound($Element) - 1 Then ExitLoop
Node($Element[$n - 1])
WEnd
EndIf
_ArrayDisplay($Element, '所有元素路径')
$oXMLDoc = 0
Exit
Func Node($strXPath)
$Nodes = _MSXML_GetChildNodes($oXMLDoc, $strXPath)
If @error = 1 Then
ElseIf $Nodes = 0 Then
$text = _MSXML_GetChildText($oXMLDoc, $strXPath)
MsgBox(0, "元素", "元素路径:" & $strXPath & @CRLF & "元素文本内容:" & $text)
Else
For $i = 1 To $Nodes
$nNodes = _MSXML_GetNodeCount($oXMLDoc, $strXPath & "/" & $Nodes[$i])
For $m = 1 To $nNodes
If $strXPath = "/" Then
$sPath = $Nodes[$i]
Else
$sPath = StringReplace($strXPath & "/" & $Nodes[$i] & "[" & $m & "]", "", "")
EndIf
_ArraySearch($Element, $sPath)
If @error Then _ArrayAdd($Element, $sPath)
Next
Next
EndIf
EndFunc ;==>Node
回复 10# shqf
大虾,麻烦上传一下_MSXML.au3文件,我在论坛里搜不到啊! 。autoit3.3.9.0中有ACN_MSXML.au3,在UserInclude目录中。程序中你将_MSXML.au3 改成ACN_MSXML.au3 也行的。
页:
[1]