VTD-XML JAVA XMLModifier删除空白问题
问题描述:
我想使用XMLModifier使用下面的代码删除一些节点。我结束之间的空白。我怎样才能摆脱这一点?VTD-XML JAVA 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执行的示例代码
答
异常是由碎片重叠,当你调用名为节点expandWhiteSpaces
造成明显...第一个Size的尾部空白将与第二个“size”元素的前导空白重叠。修复方法是致电
public final long expandWhiteSpaces(long l,
short actionType)
对于操作类型,请使用WS_LEADING。这应该为你做。
我会仔细研究一下,然后回复你......一个快速评论:你将nodeName提取到一个字符串中,这不是最优的......你可以使用matchElement(String s)直接比较节点名称,不会创建中间字符串,从而节省创建和收集对象/字符串的单次往返。 –