Java XOM规范化 - 虚假角色

时间:2010-10-31 21:27:38

标签: java xml

我正在使用XOM来规范化某些XML。但是输出前面有一些奇怪的字符。代码的核心如下:

String result;
outputstream = new ObjectOutputStream(bytestream);
Builder builder = new Builder();
Canonicalizer canonicalizer = new Canonicalizer(outputstream, Canonicalizer.EXCLUSIVE_XML_CANONICALIZATION);
nu.xom.Document input = builder.build(xml, uri);
Node node = input.getRootElement();
String xpath = "//a:head";
XPathContext context = new XPathContext("a", "http://example.com/a");
Nodes nodes = node.query(xpath, context);
if (nodes.size() > 0) {
    canonicalizer.write(nodes.get(0));
    outputstream.close();
    result = bytestream.toString("UTF8");
}

xml包含

<a:envelope   xmlns:b='http://example.com/b'   xmlns:a="http://example.com/a">
  <a:document>
    <a:head>
      <b:this>this</b:this>
      <b:that>that</b:that>
      <b:what />
    </a:head>
    <a:body>
    </a:body>
  </a:document>
</a:envelope>

当结果显示在JTextarea中时,在第一个<之前显示六个意外字符。字节流中字节的十进制值是-84,-19,0,5,119,-36,60。 (接下来是规范的XML)。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题在于,由于某种原因,我无法理解,在 ObjectOutputStream 中包装了一个ByteArrayOutputStream。所以推测输出的前缀是对象元数据的一些序列化。

我直接使用了ByteArrayOutputStream,输出现在正如我所料。

    String result = "error";
    String uri = "http://example.com/uri";
    String xpath = textArea.getText();
    ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    try {
        Builder builder = new Builder();
        Canonicalizer canonicalizer = new Canonicalizer(bytestream, 
                Canonicalizer.EXCLUSIVE_XML_CANONICALIZATION);
        nu.xom.Document input = builder.build(xml, uri);
        Node node = input.getRootElement();
        XPathContext context = new XPathContext("a", "http://example.com/a");
        Nodes nodes = node.query(xpath, context);
        if (nodes.size() > 0) {
            canonicalizer.write(nodes.get(0));
            bytestream.close();
            result = bytestream.toString("UTF8");
        }
    catch (...){ ... }