java - 使用 sax 解析器读取嵌套标签

标签 java xml sax

我正在尝试读取带有以下标记的 xml 文件,但 sax 解析器无法读取嵌套标记,如

<active-prod-ownership>
  <ActiveProdOwnership>
    <Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
  </ActiveProdOwnership>
</active-prod-ownership> 

这是我使用的代码

public class LoginConsumerResponseParser extends DefaultHandler {
 // ===========================================================
 // Fields
 // ===========================================================
 static String str="default";
 private boolean in_errorCode=false;
 private boolean in_Ack=false;
 private boolean in_activeProdOwnership= false;
 private boolean in_consumerId= false;
 private boolean in_consumerAccToken=false;


  public void startDocument() throws SAXException {
  Log.e("i am ","in start document");
 }


 public void endDocument() throws SAXException {
  // Nothing to do
  Log.e("doc read", " ends here");
 }

 /** Gets be called on opening tags like: 
  * <tag> 
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/

 public void startElement(String namespaceURI, String localName,
   String qName, Attributes atts) throws SAXException {
  if(localName.equals("ack")){
   in_Ack=true;
  }
  if(localName.equals("error-code")){
   in_errorCode=true;
  }
  if(localName.equals("active-prod-ownership")){
   Log.e("in", "active product ownership");
   in_activeProdOwnership=true;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= true;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= true;
  }
 }

 /** Gets be called on closing tags like: 
  * </tag> */

 public void endElement(String namespaceURI, String localName, String qName)
 throws SAXException {
  if(localName.equals("ack")){
   in_Ack=false;
  }
  if(localName.equals("error-code")){
   in_errorCode=false;
  }
  if(localName.equals("active-prod-ownership")){
   in_activeProdOwnership=false;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= false;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= false;
  }
 }

 /** Gets be called on the following structure: 
  * <tag>characters</tag> */

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

  if(in_Ack){
  str= new String(ch,start,length);
  }
  if(str.equalsIgnoreCase("success")){
  if(in_consumerId){

  }
  if(in_consumerAccToken){

  }
  if(in_activeProdOwnership){
   str= new String(ch,start,length);
   Log.e("active prod",str);
  }
  }
 }
}

但是在到达标签 in_activeProdOwnersip 时只读取“<”作为标签的内容

请帮助我读取整个数据

最佳答案

您的 XML 文件中的标记与解析器不匹配。我认为您将标签与属性名称混淆了。以下是正确解析示例 XML 的代码:

public class LoginConsumerResponseParser extends DefaultHandler {
    public void startDocument() throws SAXException {
        System.out.println("startDocument()");
    }

    public void endDocument() throws SAXException {
        System.out.println("endDocument()");
    }

    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes attrs) 
        throws SAXException {

        if (qName.equals("ActiveProdOwnership")) {
            inActiveProdOwnership = true;
        } else if (qName.equals("Product")) {
            if (!inActiveProdOwnership) {
                throw new SAXException("Product tag not expected here.");
            }
            int length = attrs.getLength();
            for (int i=0; i<length; i++) {
                String name = attrs.getQName(i);
                System.out.print(name + ": ");
                String value = attrs.getValue(i);
                System.out.println(value);            
            }
        }            
    }

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

        if (localName.equals("ActiveProdOwnership"))
            inActiveProdOwnership = false;
    }

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

    public static void main(String args[]) throws Exception {
        String xmlFile = args[0];
        File file = new File(xmlFile);
        if (file.exists()) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new Test();
            parser.parse(xmlFile, handler);
        }
        else {
            System.out.println("File not found!");
        }
    }

    private boolean inActiveProdOwnership = false;
}

示例运行将产生以下输出:

startDocument()
code: 3N3
component: TRI_SCORE
orderNumber: 1-77305469
endDocument()

关于java - 使用 sax 解析器读取嵌套标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4489208/

相关文章:

java - 在新线程中 toast

java - 如何将 Int 传递给 Java 中的 Soap 请求

c# - 在 DLL 中为参数添加注释

javascript - 带有 XML 负载的 Jquery POST 调用

java - 根据第一个元素对子数组进行排序

java - 将 XML 拆分为多个 xml 文件

java - 如何按节点/元素名称迭代 XML

java - SAX 解析 - 将嵌套标签映射到主标签

java - 如何链接两个不同的元素

java - 我可以在 jsp/servlet 或控制台应用程序中打开多少个数据库连接?