Dom解析的文章已經爛大街了。在這裡,只舉三個場景下如何編碼的例子:
詳細的講解看官請自行百度。
dom4j包下載鏈接為:點擊下載dom4j
xml實例
<model name="model">
<operator name="kafkaInput">
<parameter name="inputTopicName" value="department1_tn1"/>
</operator>
<operator name="addFielduuid">
<parameter name="parameter1" value="p1"/>
</operator>
<operator name="kafkaOutput">
<parameter name="outTopicName" value="department1_tn1"/>
</operator>
<connect from="kafkaInput.outport1" to="addFielduuid.inport1"/>
<connect from="addFielduuid.outport1" to="kafkaOutput.inport1"/>
<ouput path="/home"/>
</model>
獲取這三個節點的代碼為:
publicstaticvoidparsingSameNameNode(String xmlPath) {
File file = new File(argsPath);
// 創建saxReader對象
SAXReader reader = new SAXReader();
// 通過read方法讀取一個文件 轉換成Document對象
Document document;
try {
document = reader.read(file);
List<Element> operators = document.selectNodes("/model/operator");
for(Element operator:operators){
//do something...
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
注意解析前讀取xml內容、構建Document實例的代碼:
File file = new File(argsPath);
// 創建saxReader對象
SAXReader reader = new SAXReader();
// 通過read方法讀取一個文件 轉換成Document對象
Document document;
try {
document = reader.read(file);
//do something...
} catch (DocumentException e) {
e.printStackTrace();
}
轉換代碼如下:
// 獲取根節點元素對象
Element rootNode = document.getRootElement();
// 獲取context節點所有文字內容
String context = rootNode.element("context").asXML();
例上面xml中,output節點的path屬性值修改為:/home/BYRans,代碼如下:
Element rootNode = document.getRootElement();
Element node = rootNode.element("/model/output");
Attribute path = node.attribute("path");
path.setValue("/home/BYRans");
例上面xml中,output節點的path屬性值修改為:/home/BYRans,代碼如下:
Element rootNode = document.getRootElement();
Element node = rootNode.element("/model/output");
node.setAttributeValue("path","/home/BYRans");