做一个应解析XML并得到一些信息的VBScript,这是XML的一个例子:
<?xml version="1.0" encoding="windows-1251"?>
<Performance>
<Group>EX-007
<Student>
<Name>testname</Name><ID>12345</ID>
<Subject>Informatics
<Semester>1<Mark>
<Exam>5</Exam>
</Mark></Semester></Subject>
<Subject>Phys
<Semester>2<Mark>
<PersonalTask>4</PersonalTask>
<Exam>3</Exam>
</Mark></Semester></Subject>
</Student>
</Group>
</Performance>
这是VBScript代码:
Set xml = CreateObject("Msxml.DOMDocument")
success = xml.Load("data1.xml")
Set root = xml.DocumentElement
Set nodes = root.SelectNodes("Group")
WScript.Echo(nodes(0).text)
我想在控制台中输出“EX-007”,而是输出组标签下的整个树。这有什么不对?
答案 0 :(得分:0)
您的XML设计不合理,因为您的某些节点包含文本节点和子节点。您可以通过替换子节点中的文本来解决这个问题:
Set re = New RegExp
re.Pattern = "^\s+|\s+$"
For Each node In xml.SelectNodes("//Group")
txt = Replace(node.text, node.SelectSingleNode("./Student").text, "")
WScript.Echo re.Replace(txt)
Next
但是,更好的解决方案是正确构建XML数据,例如通过将嵌套文本移动到其节点的属性:
<?xml version="1.0" encoding="windows-1251"?>
<Performance>
<Group Name="EX-007">
<Student>
<Name>testname</Name>
<ID>12345</ID>
<Subject Title="Informatics">
<Semester Number="1">
<Mark>
<Exam>5</Exam>
</Mark>
</Semester>
</Subject>
<Subject Title="Phys">
<Semester Number="2">
<Mark>
<PersonalTask>4</PersonalTask>
<Exam>3</Exam>
</Mark>
</Semester>
</Subject>
</Student>
</Group>
</Performance>
这样您就可以直接选择信息,如下所示:
For Each node In xml.SelectNodes("//Group/@Name")
WScript.Echo node.text
Next