xml 파일을 구문 분석 할 때 dom4j과 xpath을 사용하고 있으며 질문이 만났습니다. xmlns 선언이 있으면 xPath는 아무 것도 반환하지 않지만 네임 스페이스 선언이 제거되면 xPath가 올바르게 작동하고 기대 한 가치를 되 찾을 것입니다.dom4j를 사용하여 xml 네임 스페이스 선언을 제거하는 방법은 무엇입니까?
가 여기 내 자바 테스트 파일입니다
public class XPathTest {
public static void main(String[] args) {
testXPath();
}
public static void testXPath(){
Document doc=getDocument("file/info.xml");
Element root=doc.getRootElement();
/*boolean removeFlag=root.remove(root.getNamespace());
System.out.println("removeFlag:\t"+removeFlag);*/
Node node=root.selectSingleNode("list[@id='002']/name");
System.out.println(node.getText());
}
public static Document getDocument(String file){
Document document=null;
SAXReader saxReader=null;
try {
saxReader=new SAXReader();
document= saxReader.read(new File(file));
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
}
}
가 여기 내 XML 파일입니다 : 내 테스트 프로그램을 실행하면, 나는 NullPointerException이 stack.However있어
<?xml version="1.0" encoding="utf-8"?>
<info xmlns="http://fit42.sys42.vwg/emx">
<intro>信息</intro>
<list id='001'>
<head>auto_userone</head>
<name>Jordy</name>
<number>12345678</number>
<age>20</age>
<sex>Man</sex>
<hobby>看电影</hobby>
</list>
<list id='002'>
<head>auto_usertwo</head>
<name>tester</name>
<number>34443678</number>
<age>18</age>
<sex>Man</sex>
<hobby>玩游戏</hobby>
</list>
<taichung id='003'>
<mayor>Jason Hu</mayor>
</taichung>
</info>
, xml에 대한 네임 스페이스 선언을 제거하고 아래와 같이하면 모든 것이 제대로 작동합니다.
<?xml version="1.0" encoding="utf-8"?>
<info>
<intro>信息</intro>
<list id='001'>
<head>auto_userone</head>
<name>Jordy</name>
<number>12345678</number>
<age>20</age>
<sex>Man</sex>
<hobby>看电影</hobby>
</list>
<list id='002'>
<head>auto_usertwo</head>
<name>tester</name>
<number>34443678</number>
<age>18</age>
<sex>Man</sex>
<hobby>玩游戏</hobby>
</list>
<taichung id='003'>
<mayor>Jason Hu</mayor>
</taichung>
</info>
그러나 때문에 XML 파일이 다른 회사에서 얻을 나는 그것의 구조를 수정할 수 없습니다, 그래서 내 progaram에서 네임 스페이스 선언을 제거하기 위해 시도되는 16,는, 나는 아래와 같이 testXPath 방법을 수정 진정한 액션 수익을 제거하고 프로그램이 여전히 NullPointerException이 발생, 그래서 나는 여전히 rootElement에서 XML 선언을 볼 수 있습니다, 나는 이유를 알고하지 않습니다
public static void testXPath(){
Document doc=getDocument("file/info.xml");
Element root=doc.getRootElement();
boolean removeFlag=root.remove(root.getNamespace());
System.out.println("removeFlag:\t"+removeFlag);
Node node=root.selectSingleNode("list[@id='002']/name");
System.out.println(node.getText());
}
그래서 내 질문은 : 누군가가 나에게 줄 수 솔 (sol) 방법에 대한 조언 그거야? 요소 이름 또는 속성이 caratere의 UTF8 또는 당신이 XPATH에서 함수를 사용해야합니다 네임 스페이스를 speciefied 한 당신의 XML의 이름이 있으면
보통 NamespaceManager 인스턴스를 취 SelectSingleNode의 과부하,있다 :
이 코드가 작동합니다. 네임 스페이스를 제거하지 않으면 전달하므로 XPath는 완전 일치를 찾습니다. 사실 네임 스페이스의 핵심입니다. –
@ TonyHopkinson 당신이 쓴 것처럼 노력했지만 dom4j API에서 오버로드 메서드를 찾지 못했습니다. 좀 더 명확하게 대답 할 수 있습니까? 감사합니다. – lucumt
왜 네임 스페이스가 실제로 _use_ 네임 스페이스가 아닌가요? 또는 최소한 와일드 카드 네임 스페이스 연산자 (예 :'* : list [@ id = '002']/* : name')를 사용하십시오. 결국 이것은 네임 스페이스의 의도 된 사용입니다. – dirkk