测试 XML 属性 [英] Testing for an XML attribute

查看:8
本文介绍了测试 XML 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段这样的 XML:

I have a piece of XML like so:

<root>
    <foo src=""/>
    <foo src="bar"/>
    <foo />
</root>

我想知道哪些元素有 src 属性,哪些是空的,哪些有值.

I want to know which elements have a src attribute, which are empty and which have values.

我走得最远的地方是

$ xmlstarlet sel -t -m '//foo' -v @src -n foo.xml 

bar

虽然这并没有告诉我第三个 foo 缺少该属性.

Though that doesn't tell me the third foo is missing the attribute.

推荐答案

这将选择没有 src 属性的 foos.

This will select the foos with no src attribute.

/root/foo[not(@src)]

对于其他两项任务,我将使用@TOUDIdel 和@Dimitre Novatchev 指出的表达式的混合:/root/foo[@src and string-length(@src)=0] 用于带有空 src/root/foo[@src 的 foos和 string-length(@src)!=0] 用于带有 src 内容的 foos.

For the other two tasks, I would use a mix of the expressions pointed out by @TOUDIdel and @Dimitre Novatchev: /root/foo[@src and string-length(@src)=0] for foos with an empty src, and /root/foo[@src and string-length(@src)!=0] for foos with an src with content in it.

顺便说一句,我会避免使用任何地方"选择器,//(更不用说 * 通配符),除非您确定这是特别是你需要什么.// 就像让你非常渴望的狗嗅一块布并告诉它,把所有闻起来像这样的东西都给我,无论你在哪里找到它".你不会相信它可以决定带回来的奇怪的废话.

As an aside, I would avoid using the "anywhere" selector, // (not to mention the * wildcard), unless you're sure that this is specifically what you need. // is like making your very eager dog sniff a piece of cloth and telling it, "bring me everything that smells like this, wherever you find it". You won't believe the weird crap it can decide to bring back.

这篇关于测试 XML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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