代码之家  ›  专栏  ›  技术社区  ›  RedGrittyBrick

Java XOM规范化-伪字符

  •  1
  • RedGrittyBrick  · 技术社区  · 15 年前

    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>
    

    < . 字节流中字节的十进制值为-84、-19、0、5119、-36、60。(后面是规范的XML)。

    我做错什么了?

    1 回复  |  直到 15 年前
        1
  •  2
  •   RedGrittyBrick    15 年前

    问题是,由于某种原因,我无法理解,我把一个bytearyoutputstream包在一个 . 因此,可能输出的前缀是对象元数据的某种序列化。

    我刚刚直接使用了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 (...){ ... }