Я пытаюсь добавить атрибуты row и col в xml. Но когда он вызывает метод tagItem()
, он выдает ошибку:
nNode.getChildNodes () должен вернуть список всех элементов в виде списка узлов, но он возвращает следующую строку.
После получения ChildNode я хочу выполнить итерацию и добавить столбец и позицию строки.
Ввод:
<container title="S1">
<item type="pl"
id="p1"/>
<item type="pl"
id="p2"/>
</container>
Ожидаемый выход:
<container title="S1"
row="1">
<item type="pl"
id="p1"
row="1"
col="1"/>
<item type="pl"
id="p2"
row="1"
row="1"/>
public static void main(String[] args) throws Exception {
String xml = "<container title=\"S1\"\n" +
"row=\"1\">\n" +
" <item type=\"pl\"\n" +
" id=\"p1\"\n" +
" row=\"1\"\n" +
" col=\"1\"/>\n" +
" <item type=\"pl\"\n" +
" id=\"p2\"\n" +
" row=\"1\"\n" +
" row=\"1\"/>\n" +
"</container>" ;
tagContainer(xml , "container");
}
private static void tagContainer(String xml , String nodeName) {
Document doc = convertStringToXMLDocument(xml);
NodeList nodelist = doc.getElementsByTagName(nodeName) ;
for(int i =0 ; i < nodelist.getLength() ; i++){
Node nNode = nodelist .item(i);
Attr at = doc.createAttribute("original_row_pos");
at.setValue(i+"");
nNode.getAttributes().setNamedItem(at);
tagItem(nNode.getChildNodes() ,doc , i+"") ;
}
}
private static void tagItem(NodeList nodelist ,Document doc , String row_pos) {
for(int i =0 ; i < nodelist.getLength() ; i++){
Attr row = doc.createAttribute("original_row_pos");
row.setValue(i+"");
nodelist.item(i).getAttributes().setNamedItem(row);
Attr col = doc.createAttribute("original_col_pos");
col.setValue(i+"");
nodelist.item(i).getAttributes().setNamedItem(col);
}
}