【发布时间】:2012-04-14 17:33:52
【问题描述】:
我有一个带有 xml 标记的 sax 解析器,其中包含以下文本:“A & amp; B”(那里没有空格 - 添加因此它不会在此处转换为 &)
就好像它被转换了两次,并且由于“A”的结果而由于&符号而转义。流程如下:
Xml 文件已下载
InputStream _inputStream = _urlConnection.getInputStream();
BufferedInputStream _bufferedInputStream = new BufferedInputStream(_inputStream);
ByteArrayBuffer _byteArrayBuffer = new ByteArrayBuffer(64);
int current = 0;
while((current = _bufferedInputStream.read()) != -1)
{
_byteArrayBuffer.append((byte)current);
}
FileOutputStream _fileOutputStream = openFileOutput(_file, MODE_PRIVATE);
_fileOutputStream.write(_byteArrayBuffer.toByteArray());
_fileOutputStream.close();
数据在 endElement 中用 Sax 转换
else if (inLocalName.equalsIgnoreCase(_nodeTitle))
{
_titleValue = currentValue;
currentValue = "";
}
在调试中,当我在处理程序的字符方法中读取时,与号已经转换并且数据被截断。
我已经看到了很多关于这个的问题,但从来没有一个解决方案。有什么想法吗?
谢谢
解析器:
List<PropertiesList> _theList = null;
try
{
// Create Factory, Parser, Reader, Handler
SAXParserFactory _saxParserFactory = SAXParserFactory.newInstance();
SAXParser _saxParser = _saxParserFactory.newSAXParser();
XMLReader _xmlReader = _saxParser.getXMLReader();
HandlerReps _handler = new HandlerReps(inRegion, inAbbreviation);
_xmlReader.setContentHandler(_handler);
_xmlReader.parse(new InputSource(inStream));
_theList = _handler.getTheList();
}
处理程序:
// Called when Tag Begins
@Override
public void startElement(String uri, String inLocalName, String inQName, Attributes inAttributes) throws SAXException
{
currentElement = false;
}
// Called when Tag Ends
@Override
public void endElement(String inUri, String inLocalName, String inQName) throws SAXException
{
currentElement = false;
// Title
if (inLocalName.equalsIgnoreCase(_nodeValue))
{
if (_stateValue.equalsIgnoreCase(_abbreviation) &&
_countryValue.equalsIgnoreCase(_region))
{
// Construct the object
PropertiesRegion _regionObject = new PropertiesRegion(_titleValue, _address1Value);
cList.add(_regionObject);
Log.d(TAG, _regionObject.toString());
}
_titleValue = "";
_address1Value = "";
}
// Title
else if (inLocalName.equalsIgnoreCase(_nodeTitle))
{
_titleValue = currentValue;
currentValue = "";
}
// Address1
else if (inLocalName.equalsIgnoreCase(_nodeAddress1))
{
_address1Value = currentValue;
currentValue = "";
}
}
// Called to get Tag Characters
@Override
public void characters(char[] inChar, int inStart, int inLength) throws SAXException
{
if (currentElement)
{
currentValue = new String(inChar, inStart, inLength);
currentElement = false;
}
}
【问题讨论】:
-
请向我们展示更多实际解析 XML 的代码。从 URL 下载东西到文件很无聊。 :-) 除非你在 openFileOutput() 中做错了什么。此外,这里的下载效率很低,但这是一个不同的问题。简而言之:不要使用 InputStream/OutputStream 的单字节方法。
-
我添加了下载代码,以防有一些我不知道的相关内容 - 如 &那时正在转换。我使用 DOM 解析器完成了完全相同的过程,但性能无法接受。不过输出是正确的。
-
仍然没有足够的上下文,但我还是试了一下。请参阅下面的答案。
-
不知道还能给你什么 - 这是完整的解析器和处理程序减去异常和初始化变量。
-
好吧,我们不知道 HandlerReps 是什么,getTheList() 等。但是无论如何,请参阅下面的答案,相应地修复您的代码,您会没事的。