gpt4 book ai didi

Java XOM 规范化 - 虚假字符

转载 作者:行者123 更新时间:2023-11-30 05:09:11 24 4
gpt4 key购买 nike

我正在使用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)。

我做错了什么?

最佳答案

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

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

关于Java XOM 规范化 - 虚假字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com