Xml 节点文本在包含有趣字符时会导致问题 [英] Xml node text is causing issues when it has funny characters

查看:36
本文介绍了Xml 节点文本在包含有趣字符时会导致问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下事件中设置 xml 元素内的字符:

 public void characters(char[] ch, int start, int length) {elementText = new String(ch, start, length);}

其中 elementText 是一个字符串.

#<ABC::DEF::GHI:0x102548f78></client-key>

我正在将此 xml 数据加载到 java 对象中,并且我的对象属性具有此值:

 '\n '

现在,如果我更改上面元素 <client-key> 中的文本,它会在我的对象属性中正常显示.

是否有一些编码问题需要我以某种方式处理?

public void endElement(String uri, String localName, String qName) {if (qName.equals("client-key")) {client.setClientKey(elementText);}}

解决方案

如果您的 xml 看起来像这样,您可能会得到:

#<ABC::DEF::GHI:0x102548f78></客户端密钥>

参见 ContentHandler<块引用>

字符
...
Parser 将调用此方法来报告每个字符数据块.SAX 解析器可以在一个块中返回所有连续的字符数据,或者他们可以将它分成几个块;...

您最好使用以下内容:

public void characters(char[] ch, int start, int length) {//注意 +=elementText += new String(ch, start, length);}public void endElement(String uri, String localName, String qName) {if (qName.equals("client-key")) {client.setClientKey(elementText);}elementText = "";}

I'm setting the characters inside the xml element in the following event:

 public void characters(char[] ch, int start, int length) {
        elementText = new String(ch, start, length);
    }

Where elementText is a String.

<client-key>#&lt;ABC::DEF::GHI:0x102548f78&gt;</client-key>

I am loading this xml data into java objects, and my objects property has this value:

 '\n        '

Now if I change the text in the element <client-key> above, it comes out fine in my objects property.

Is there some encoding issue that I need to handle somehow?

public void endElement(String uri, String localName, String qName) {

       if (qName.equals("client-key")) {
            client.setClientKey(elementText);
        }

}

解决方案

This is probably what you would get if your xml has been tidied to look like:

<client-key>
    #&lt;ABC::DEF::GHI:0x102548f78&gt;
</client-key>

See ContentHandler

characters
...
The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; ...

You'd be better off using something like:

public void characters(char[] ch, int start, int length) {
  // Note the +=
  elementText += new String(ch, start, length);
}

public void endElement(String uri, String localName, String qName) {

  if (qName.equals("client-key")) {
    client.setClientKey(elementText);
  }
  elementText = "";
}

这篇关于Xml 节点文本在包含有趣字符时会导致问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆