繁体   English   中英

无法使用Java从xml读取特殊字符

[英]Unable to read special characters from xml using java

当我尝试使用SAX解析器从Java读取xml时,无法读取特殊字符后存在的元素中的内容

例如:

<title>It's too difficult</title>

使用SAX解析器读取之后,它只是显示

如何处理特殊字符。 我的示例代码如下

    package com.test.java;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLUsingSAXParser {




  public static void main(String argv[]) {

   try {

      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();

      DefaultHandler handler = new DefaultHandler() {

      int titleCount;
      boolean title = false;
      boolean description = false;

      public void startElement(String uri, String localName,
         String qName, Attributes attributes)
         throws SAXException {

        // System.out.println("Start Element :" + qName);


         if (qName.equalsIgnoreCase("title")) {
            title = true;
            titleCount+=1;
         }

         if (qName.equalsIgnoreCase("description")) {
            description = true;
         }

      }

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

         //  System.out.println("End Element :" + qName);

      }

      public void characters(char ch[], int start, int length)
          throws SAXException {


           if (title&&titleCount>2) {
               System.out.println("title : "
                   + new String(ch, start, length)+":"+titleCount);
               title = false;
            }

           if (description) {
               System.out.println("description : "
                   + new String(ch, start, length));
               description = false;
            }

         }

       };

       saxParser.parse("C:\\Documents and Settings\\sukumar\\Desktop\\sample.xml", handler);

     } catch (Exception e) {
       e.printStackTrace();
     }
   }

 }

characters(char ch[], int start, int length)方法不会读取整行,您应该将字符存储在StringBuffer ,并在endElemen方法中使用它。

例如:

private StringBuffer buffer = new StringBuffer();

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

     if (qName.equalsIgnoreCase("title")) {
        System.out.println("title: " + buffer);
     }else if (qName.equalsIgnoreCase("description")) {
        System.out.println("description: " + buffer);
     }
     buffer = new StringBuffer();
}

public void characters(char ch[], int start, int length)
      throws SAXException {
     buffer.append(new String(ch, start, length));
}

暂无
暂无

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

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