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);
}
죄송 합니다만 제안 된 해결책이 작동하지 않습니다. 이 특정 예에서 포트 요소 값은 변경되지 않았습니다. –
아, 좋아. 'setNodeValue()'대신'setTextContent()'를 시도하십시오. – Zutty
위대한 작품! 감사. –