2012-11-20 3 views
1

Java에서 xpath를 사용하여 XML 파일에서 일반 노드를 편집해야합니다. 나는 많은 다른 방법과 접근법을 시도했지만이 작업을 성공적으로 완료하는 데 성공했습니다. 아래 코드에서 언급 된 문제의 일부분을 도와주십시오. XML 파일에 대한Java에서 xpath를 사용하여 XML 파일의 일반 노드 편집

예는 내가 사용

<data-source> 
     <account-id>1102</account-id> 
     <type>ftp</type>  
     <url>http://a.b.com</url> 
     <port>21</port> 
     <username>user</username> 
     <password>12345678</password> 
     <update-frequency>1200</update-frequency> 
</data-source> 
은 다음과 인수로 내 기능입니다

: 만약 내가 제대로 이해하고

* Usage example: updateElementValue(FILE_LOCATION + "addDataSource.xml", "/data-source", "port", "80") 
* @param fileNameToUpdate - full file name (path + file name) to update 
* @param xpath - element node xpath 
* @param elementName - element name 
* @param elementValue - value to set 

    public static void updateElementValue(String fileNameToUpdate, String xpath, String elementName, String elementValue) throws Exception 
     { 
     // Exit with exception in case value is null 
     if(elementValue == null) { 
      throw new Exception("Update element Value function, elementValue to set is null"); 
     } 

     //Read the file as doc 
     File fileToUpdate = new File(fileNameToUpdate); 
     Document doc = FileUtils.readDocumentFromFile(fileToUpdate); 


     //WHAT SHOULD I DO HERE?... 


     //Save the doc back to the file 
     FileUtil.saveDocumentToFile(doc, fileNameToUpdate);   
    } 

답변

2

, 당신이 실 거예요으로, elementName 필요 XPath는 노드를 고유하게 식별해야합니다. javax.xml.xpath 패키지 ... 내가 정확하게 코드를 실행 시도하지 않은

XPathFactory xfactory = XPathFactory.newInstance(); 
XPath xpathObj = xfactory.newXPath(); 
Node node; 

try { 
    node = (Node)xpathObj.evaluate(xpath, doc, XPathConstants.NODE); 
} catch (XPathExpressionException e) { 
    throw new RuntimeException(e); 
} 

node.setTextContent(elementValue); 

를 사용하여,하지만 작동합니다.

+0

죄송 합니다만 제안 된 해결책이 작동하지 않습니다. 이 특정 예에서 포트 요소 값은 변경되지 않았습니다. –

+1

아, 좋아. 'setNodeValue()'대신'setTextContent()'를 시도하십시오. – Zutty

+0

위대한 작품! 감사. –

관련 문제