使用 VBScript 获取 XML 节点文本 [英] Getting XML node text with VBScript

查看:26
本文介绍了使用 VBScript 获取 XML 节点文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做一个应该解析 XML 并获取一些信息的 VBScript,这是一个 XML 示例:

Doing a VBScript that should parse XML and get some info, here's an example of 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 代码:

This is the VBScript code:

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"输出,但它会在组标签下输出整棵树.这里有什么问题吗?

I would like to get an "EX-007" output in console, but instead it outputs the whole tree under the group tag. What's wrong here?

推荐答案

您的 XML 设计不善,因为您的某些节点同时包含文本节点和子节点.您可以通过替换子节点中的文本来解决这个问题:

Your XML is not well-designed, because some of your nodes contain both text and child nodes. You could work around that by replacing the text from the child node(s):

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 数据,例如通过将嵌套文本移动到其节点的属性:

However, a better solution would be to structure your XML data properly, e.g. by moving the nested text to attributes of their node:

<?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>

这样你就可以直接选择信息了,像这样:

so that you can select the information directly, like this:

For Each node In xml.SelectNodes("//Group/@Name")
    WScript.Echo node.text
Next

这篇关于使用 VBScript 获取 XML 节点文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆