我正在尝试使用以下代码使用XMLModifier删除一些节点。我以两个空格结束。我怎么能摆脱这个?
import java.nio.file.Files;
import java.nio.file.Paths;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
public class VTDWhiteSpaceIssue {
public static void main(String[] args) throws Exception {
byte[] encoded = Files.readAllBytes(Paths.get("Sample.xml"));
String query = new String(encoded, "UTF-8");
VTDGen vtdGenDoc = new VTDGen();
vtdGenDoc.setDoc(query.getBytes());
vtdGenDoc.parse(false);
VTDNav vtdNav = vtdGenDoc.getNav();
AutoPilot autoPilot = new AutoPilot(vtdNav);
XMLModifier xmlModifier = new XMLModifier(vtdNav);
autoPilot.selectXPath("//product/catalog_item");
if (autoPilot.evalXPath() != -1 && vtdNav.toElement(VTDNav.FIRST_CHILD)) {
do {
String nodeName = vtdNav.toRawString(vtdNav.getCurrentIndex());
if (!"price".equals(nodeName) && !"item_number".equals(nodeName)) {
System.out.println("Removing node " + nodeName);
xmlModifier.remove();
}
} while (vtdNav.toElement(VTDNav.NEXT_SIBLING));
}
System.out.println();
System.out.println("==============================================================");
// normalizedQueryNav = normalizedQueryModifier.outputAndReparse();
xmlModifier.output(System.out);
System.out.println("==============================================================");
}
}
sample.xml中
<catalog>
<product description="Cardigan Sweater" product_image="cardigan.jpg">
<catalog_item gender="Men's">
<title>Cardigan Sweater</title>
<item_number>QWZ5671</item_number>
<size description="Medium">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
</size>
<size description="Large">
<color_swatch image="red_cardigan.jpg">Red</color_swatch>
<color_swatch image="burgundy_cardigan.jpg">Burgundy</color_swatch>
</size>
<price>39.95</price>
</catalog_item>
</product>
我尝试使用以下代码代替xmlModifier.remove()
long elementFragment = vtdNav.getElementFragment();
xmlModifier.remove(vtdNav.expandWhiteSpaces(elementFragment));
失败,出现以下异常: -
com.ximpleware.ModifyException: Invalid insertion/deletion condition detected between offset 189 and offset 373
at com.ximpleware.XMLModifier.check2(XMLModifier.java:888)
at com.ximpleware.XMLModifier.output(XMLModifier.java:1977)
at vtd.VTDWhiteSpaceIssue.main(VTDWhiteSpaceIssue.java:40)
注意: - 使用vtd-xml_2_13.jar执行的示例代码
答案 0 :(得分:0)
异常是由片段重叠引起的......显然,当您在名为“size”的节点上调用expandWhiteSpaces
时。第一个Size的尾随空格将与第二个“size”元素的前导空格重叠。修复是调用
public final long expandWhiteSpaces(long l,
short actionType)
对于操作类型,请使用WS_LEADING。那应该为你做。