如何在tcl中获取xml元素值? [英] How to get a xml element value in tcl?

查看:45
本文介绍了如何在tcl中获取xml元素值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图获取一个元素的值到一个 tcl 变量示例 stats.xml 文件

Trying to get the value of an element to a tcl variable sample stats.xml file

<account>
    <name>abc</name>
    <number>1224.3414</number>
</account>

在上面的例子中试图只提取一个元素值,名称或数字

In the above case trying to extract only one element value either name or number

set value
regexp "<$number>(.*?)</number>" stats.xml value

推荐答案

正如@Peter 所说,最好使用 tdom.尝试使用正则表达式解析 xml 将导致痛苦的世界.(参见 为什么这么糟糕用正则表达式解析 XML 的想法?)

As @Peter says, it is best to use tdom. Trying to parse xml with regexp's will lead to a world of pain. (see Why is it such a bad idea to parse XML with regex?)

也就是说,如果您坚持这样做,那么这些就是您需要对脚本进行的更改.

That said, if you insist on doing it, then these are the changes you need to your script.

首先您需要将文件的内容放入一个变量中.您正在文件名上使用正则表达式.

First you need to get the contents of the file into a variable. You are using the regexp on the file's name.

% set fp [open stats.xml]
file5
% set contents [read $fp]
<account>
    <name>abc</name>
    <number>1224.3414</number>
</account>
% close $fp

您的模式中也有错误(number 前面的 $ 符号).此外 value 将具有整个匹配.您将需要一个额外的变量(下面的 v),以获取第一个匹配项,即数字.因此,请执行以下操作:

You also have an error in your pattern (the $ sign in front of number). In addition value will have the entire match. You will need an extra variable (v below), to get just the first match, that is the number. So do the following:

% regexp "<number>(.*?)</number>" $contents value v
1
% puts $v
1224.3414

这篇关于如何在tcl中获取xml元素值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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