dom4j无法解析xml命名空间的问题

解析的xml文件:

 

<?xml version="1.0" encoding="UTF-8"?>   
<MyXML xmlns="http://www.ttt.com/ttt-TrdInfo-1-0" xmlns:x="http://www.ttt.com/ttt/metadata.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="res286.xsd">   
<Hdr>   
    <ReqId>001</ReqId>   
    <Tid>1002</Tid>   
    <Cid>500</Cid>   
    <user>cuishen</user>   
    <Mname>supermarket</Mname>     
    <pwd>543200210</pwd>   
</Hdr>   
<Car>   
    <Flg>T</Flg>   
    <Cod>ccc</Cod>   
    <Door>kkk</Door>   
    <mktId>b01</mktId>   
    <Key>   
        <KeyID>t01</KeyID>   
    </Key>   
</Car>   
</MyXML>   

 
Java代码

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();    
        }    
    }    
}    

 
上面就是运用dom4j解析带命名空间的xml文件的节点的例子,只要给XPath设置默认的命名空间就行了,这个xml文件尽管定义了其他命名空间,但是没有用到它,所以不必管它,那个HashMap里的键是随便定义的字符串,值就是默认的命名空间对应的字符串。document.createXPath()里传的参数是要读取的节点的XPath,即“//”+ HashMap里的键名 + “:”+ 要读取的节点名组成的字符串^_^

你可能感兴趣的:(xml)