简体   繁体   English

为带有“&”字符的字符串创建 XMLStreamReader

[英]Creating XMLStreamReader for a string with "&" character

I want to unmarshall a xmlString which has '&' character in it.我想解组其中包含“&”字符的 xmlString。

    XMLInputFactory xif = XmlUtils.newXMLInputFactory();
    String test = "<Res>Abc & Def</Res>";
    StringReader sr = new StringReader(test);
    try {
      XMLStreamReader reader = xif.createXMLStreamReader(sr);
      JAXBContext jaxbContext = JAXBContext.newInstance(BluelineReprintInvoiceResponseData.class);
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      Object o = unmarshaller.unmarshal(reader);
    } catch(Exception ex) {
      ex.printStackTrace();
    }

Is there any way to unmarshall the string without using replace/replaceAll to replace '&' character from the string?有没有办法在不使用 replace/replaceAll 替换字符串中的 '&' 字符的情况下解组字符串?

Is there any way to unmarshall the string without using replace / replaceAll to replace & characters in the string?有没有办法在不使用replace / replaceAll替换字符串中的&字符的情况下解组字符串?

Basically no, because that is invalid XML.基本上没有,因为那是无效的 XML。 A bare ampersand is not permitted in that context.在这种情况下,不允许使用裸 & 符号。 Any conformant XML parser will give you a parse error when it encounters that & and then doesn't find the corresponding ;任何符合标准的 XML 解析器在遇到&然后找不到对应的;时都会给你一个解析错误。

The correct solution it to fix the (so-called) XML at its source .正确的解决方案是在其源头修复(所谓的)XML。 What ever is generating that string as XML is faulty.生成该字符串为 XML 的原因是错误的。 If it is being entered by a human, the XML should be validated on entry.如果它是由人输入的,则应在输入时验证 XML。

Note that if you attempt to automatically "correct" bare ampersands in broken XML using string replacement, you risk doing other damage;请注意,如果您尝试使用字符串替换自动“纠正”损坏的 XML 中的裸 & 符号,则可能会造成其他损坏; ie IE

  • breaking character and entity references, or破坏字符和实体引用,或
  • messing up the content of CDATA sections.弄乱 CDATA 部分的内容。

The auto-correction code needs to be aware of the context in which the ampersand appears.自动更正代码需要了解 & 符号出现的上下文。 It would be difficult to do using regexes.使用正则表达式会很困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM