如何使用Java根据XML中Tag的id属性获取对应value节点值
Java 按Tag id查询XML中value值的实现方案
实现说明
- 采用JDK自带的
org.w3c.dom和javax.xml.xpath包实现,无需额外引入第三方依赖,降低新手配置成本 - 支持传入Tag的id属性值,直接返回对应
<value>标签的文本内容,查询不到时返回空字符串或null
完整代码实现
import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import java.io.File; public class XmlQueryUtils { /** * 根据Tag的id属性查询对应value标签的值 * @param xmlFilePath XML文件的完整路径 * @param tagId 要查询的Tag节点的id属性值 * @return value标签的文本内容,查询失败/不存在返回null */ public static String getValueByTagId(String xmlFilePath, String tagId) { // 1. 加载XML文件为Document对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(new File(xmlFilePath)); } catch (Exception e) { e.printStackTrace(); return null; } // 2. 构造XPath查询语句 XPath xPath = XPathFactory.newInstance().newXPath(); // XPath规则://Tag匹配所有Tag节点,[@id='xxx']筛选id属性匹配的节点,/value/text()取value下的文本 String xpathExp = String.format("//Tag[@id='%s']/value/text()", tagId); // 3. 执行查询返回结果 try { String result = xPath.evaluate(xpathExp, document); return result.isEmpty() ? null : result; } catch (Exception e) { e.printStackTrace(); return null; } } // 测试方法 public static void main(String[] args) { // 替换为你自己的XML文件实际存放路径 String xmlPath = "D:/your_path/test.xml"; // 测试查询id=1923的value System.out.println(getValueByTagId(xmlPath, "1923")); // 输出My Demo // 测试查询id=1924的value System.out.println(getValueByTagId(xmlPath, "1924")); // 输出Clientfpd } }
注意事项
- 替换测试代码中的
xmlPath为你的XML文件的实际路径,如果XML放在项目的resources目录下,可通过XmlQueryUtils.class.getClassLoader().getResource("test.xml").getPath()获取路径 - 代码中的异常处理可根据业务需求优化,比如自定义业务异常抛出,代替直接打印堆栈
内容的提问来源于stack exchange,提问作者Ron.k
相关产品推荐
相关产品推荐

