修改XML并使用VTD-XML删除旧节点

时间:2014-11-04 13:34:54

标签: java xml xpath vtd-xml

我有这样的结构:

<Hotels>
  <Hotel>
    <Name>Hotel 1</Name>
    <Phone1>11111-1</Phone1>
    <Phone2>11111-2</Phone2>
  </Hotel>
  <Hotel>
    <Name>Hotel 2</Name>
    <Phone1>22222-1</Phone1>
    <Phone2>22222-2</Phone2>
  </Hotel>
  ...
</Hotels>

我想修改每个电话号码,使其具有以下结构:

<Phone>
  <Number>11111-1</Number>
</Phone>

我提取数字并构建新节点。但我不知道我应该在什么时候删除旧的Phone1Phone2节点。

我的代码:

VTDGen vg = new VTDGen();
vg.setDoc(bytes);
vg.parse(true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);

String path = "/Hotels/Hotel";

ap.selectXPath(path);

List<StringBuilder> newNodes = new ArrayList<StringBuilder>();

int count = 0;
// first while-loop: extract all numbers and build new nodes
while(ap.evalXPath() != -1) {
  StringBuilder newNode = new StringBuilder();

  for(int i = 1; i <= 2; i++) { // 2 times, because of 2 phone numbers in every hotel
    VTDNav vn2 = vn.cloneNav();
    AutoPilot ap2 = new AutoPilot(vn2);

    // extract the phone number
    ap2.selectXPath("Phone" + i);

    if(ap2.evalXPath() == -1) { continue; }

    int textIndex = vn2.getText();
    if(textIndex == -1) { continue; }

    String phone = vn2.toString(textIndex);

    newNode.append("<Phone>")
           .append("<Number>").append(phone).append("</Number>")
           .append("</Phone>");
  }

  newNodes.add(count, newNode);
  count++;
}

// now it's time to modify the xml
XMLModifier xm = new XMLModifier(vn);

ap.selectXPath(path);

count = 0;
// second while-loop: insert the created nodes
while(ap.evalXPath() != -1) {
  xm2.insertBeforeTail(newNodes.get(count).toString());

  count++;
}

VTDNav modifiedVn = xm.outputAndReparse();

我将提取和插入拆分为两个while循环,因为@ vtd-xml-author说here只重新调整一次它的效率更高。

我无法找到删除旧Phone节点的位置,并且必须有更好的方法来执行此操作吗?

0 个答案:

没有答案