---
title: "解决dom4j无法解析xml命名空间的问题"
author: "cuishen"
date: "2006-11-26T19:29:16Z"
tags: ["C", "C#", "C++", "Java", "XML"]
categories: ["企业架构"]
slug: "dom4j-xml"
draft: false
lastmod: "2006-11-26T19:29:16Z"
id: 36054
url: "https://cuishen.iteye.com/blog/36054"
---

困扰我几周的dom4j无法解析xml命名空间的问题近日得以解决，如果这个问题也正在困扰你，看看下文也许能给你一些启发 xml文件----myXML.xml \[code] 001 1002 500 cuishen supermarket 543200210 T ccc kkk b01 t01 \[/code] 下面是用dom4j解析上面xml文件的java源文件 ---ReadMyXML.java \[code] import java.io.File; import java.util.List; import java.util.Map; import java.util.HashMap; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.XPath; import org.dom4j.Attribute; import org.dom4j.io.SAXReader; import org.dom4j.DocumentException; public class ReadMyXML{ public static void main(String args\[]){ File xmlFile = new File("c:/myXML.xml"); SAXReader xmlReader = new SAXReader(); try{ Document document = xmlReader.read(xmlFile); ///\*测试代码 适用于读取xml的节点 HashMap xmlMap = new HashMap(); xmlMap.put("mo","http://www.ttt.com/ttt-TrdInfo-1-0"); XPath x = document.createXPath("//mo:ReqId"); x.setNamespaceURIs(xmlMap); Element valueElement = (Element)x.selectSingleNode(document); System.out.println(valueElement.getText()); //\*/ }catch(DocumentException e){ e.printStackTrace(); } } } \[/code] 上面就是运用dom4j解析带命名空间的xml文件的节点的例子，只要给XPath设置默认的命名空间就行了，这个xml文件尽管定义了其他命名空间，但是没有用到它，所以不必管它，那个HashMap里的键是随便定义的字符串，值就是默认的命名空间对应的字符串。document.createXPath()里传的参数是要读取的节点的XPath，即“//”+ HashMap里的键名 + “:”+ 要读取的节点名组成的字符串，简单吧，后面怎么做我就不用说了吧^\_^ 如果要读取的是xml文件里的属性该怎么办呢，不用急，看看下面的例子你就明白了，原理一样，只要在造XPath字符串的时候在属性前加个“@”就行了。 xml文件----myXML2.xml \[code] \[/code] 解析上面xml文件的java文件如下 ---ReadMyXML2.java \[code] import java.io.File; import java.util.List; import java.util.Map; import java.util.HashMap; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.XPath; import org.dom4j.Attribute; import org.dom4j.io.SAXReader; import org.dom4j.DocumentException; public class ReadMyXML2{ public static void main(String args\[]){ File xmlFile = new File("c:/myXML2.xml"); SAXReader xmlReader = new SAXReader(); try{ Document document = xmlReader.read(xmlFile); ///\*测试代码 解析xml的属性 HashMap xmlMap = new HashMap(); xmlMap.put("mo","http://www.ttt.com/ttt-TrdInfo-1-0"); XPath x = document.createXPath("//mo:Hdr/@ReqId"); x.setNamespaceURIs(xmlMap); Attribute valueAttribute = (Attribute)x.selectSingleNode(document); System.out.println(valueAttribute.getText()); //\*/ }catch(DocumentException e){ e.printStackTrace(); } } } \[/code]