【问题标题】:XStream apostrophe Issue in converting Java Object to XML将 Java 对象转换为 XML 时的 XStream 撇号问题
【发布时间】:2014-12-01 15:22:53
【问题描述】:

我正在使用 com.thoughtworks.xstream.XStream 来生成 xml 字符串。我将 Object 解析为 xstream.toXML 方法,并根据我需要的方式获取 xml 输出。

    <myxml>
      <test type="test" name="test">
        <question id="Name" answer="Micheal"/>
        <question id="Address" answer="Home">
          <details name="First Address">
            <detailanswer>friend&apos;s House</detailanswer>
          </details>
        </basequestion>
      </test>
    </myxml>

XStream xstream = new XStream();
xstream.alias("myxml", MyXml.class);
xstream.alias("test", Test.class);
xstream.alias("question", Question.class);
xstream.alias("details", Details.class);
xstream.alias("detailanswer", String.class);
xstream.addImplicitCollection(MyXml.class, "test");
xstream.addImplicitCollection(Test.class, "question");
xstream.addImplicitCollection(Question.class, "details");
xstream.addImplicitCollection(Details.class, "detailanswer");

xstream.useAttributeFor(Test.class, "type");
xstream.useAttributeFor(Test.class, "name");

xstream.useAttributeFor(Question.class, "id");
xstream.useAttributeFor(Question.class, "answer");
xstream.useAttributeFor(Details.class, "name");

return xstream.toXML(eform);

以下是对象结构。

Inside MyXml there is List<Test>
Test has List<Question>, String type, String name
Question has List<Details>, String id, String answer.
Details has List<String> detailAnswer, String name

所以问题中的元素 Friend's house 被添加到 Details 类的 List detailAnswer 中。

我得到friend&amp;apos;s House 而不是friend's house。我该如何解决这个问题。有没有使用 XStream 进行转换的特殊方法?

【问题讨论】:

  • 也提供您的 POJO 代码。
  • 更新了问题
  • &amp;apos; 与 XML 中的 ' 含义相同,因此并没有真正的错误,只是不同。尝试其他 XStream 驱动程序,例如 StaxDriver,看看是否有帮助。
  • 是的,但问题是当这个字符串保存为 xml 文件时,我得到了 '而不是 ' 这是不可接受的。我更改了 XML 结构名称,但它实际上是针对业务应用程序的
  • 当文件的接收者解析它时,他们的解析器会将&amp;apos;透明地转回'。他们的代码甚至不知道原始文档中使用了哪种表示形式。

标签: java xml xml-parsing xstream apostrophe


【解决方案1】:

我觉得用java方法替换一个字符比较好。

xStream.toXML(testPojo).replaceAll("&apos;", "'")

【讨论】:

  • 请注意,这可能会破坏撇号确实需要作为实体引用进行转义的地方,例如在使用单引号分隔符序列化的属性值中。
猜你喜欢
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
相关资源
最近更新 更多