You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xmllint提取XML中url-pattern报错,求正确命令

提取web.xml中所有节点内容的正确xmllint命令

问题场景

需要从以下web.xml文件中读取所有<url-pattern>节点的内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>APP Services</display-name>
    <servlet-mapping>
        <servlet-name>LoginLogoutMapping</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <security-constraint>
      <web-resource-collection>
      <web-resource-name >APP restricted URLs</web-resource-name>
      <url-pattern>/services.jsp</url-pattern>
      <url-pattern>/Debug.jsp</url-pattern>
      <url-pattern>/encode.jsp</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
    </security-constraint>
</web-app>

用户尝试执行以下命令时出现报错:

sh-4.4$ xmllint --xpath '//web-app/security-constraint/web-resource-collection/web-resource-name/' /optconf/web.xml

报错信息:

XPath error : Invalid expression
XPath evaluation failure

错误原因

  1. XPath表达式末尾多了斜杠,属于无效语法
  2. 目标节点指定错误,应该是url-pattern而非web-resource-name
  3. 忽略了XML的命名空间(xmlns="http://java.sun.com/xml/ns/javaee"),直接用节点名匹配会失败

正确命令

方法一:处理命名空间前缀

xmllint --xpath '//x:url-pattern/text()' --namespace-prefixes --noout /optconf/web.xml
  • --namespace-prefixes:让xmllint自动识别XML中的命名空间并分配前缀(默认用x:对应目标命名空间)
  • //x:url-pattern/text():匹配所有对应命名空间下的url-pattern节点,提取其文本内容
  • --noout:避免输出整个XML文件,只显示匹配结果

方法二:忽略命名空间匹配

xmllint --xpath '//*[local-name()="url-pattern"]/text()' /optconf/web.xml
  • local-name():只匹配节点的本地名称,忽略命名空间限制,无需额外参数处理命名空间,兼容性更强

执行任意一种命令后,都会输出所有<url-pattern>的内容:

/login
/services.jsp
/Debug.jsp
/encode.jsp

内容的提问来源于stack exchange,提问作者Blue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:23:31