简体   繁体   English

如何使用 SAX 解析器从字符串中获取子句中的所有数据?

[英]How to get all the data from clause from a string with SAX parser?

I have an application in response I get some data which I store into the string like below I我有一个应用程序作为响应,我得到了一些数据,这些数据存储在字符串中,如下所示

Want all clause data like all & how can I get?想要所有的子句数据,我怎样才能得到?

Here is my code.这是我的代码。

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class soaparse {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        String ss = 
        "<![CDATA[<translation>"+
     "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
     "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
     "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
     "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
     "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
     "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
     "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
     "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
     "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
     "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
     "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
     "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
     "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
     "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
    "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
     "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
     "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
     "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
     "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
     "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
     "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
     "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
     "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
     "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
     "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
     "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
     " </translation>]]>"; 

         DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource in = new InputSource();
            in.setCharacterStream(new StringReader(ss));

            Document doc = db.parse(in);
            NodeList nodes = doc.getElementsByTagName("GetTranslationResult");

         for (int i = 0; i < nodes.getLength(); i++) {
              Element element = (Element) nodes.item(i);

              NodeList name = element.getElementsByTagName("en");
              Element line = (Element) name.item(i);
              System.out.println("Name: " + getCharacterDataFromElement(line));

              NodeList title = element.getElementsByTagName("alt");
              line = (Element) title.item(i);
              System.out.println("Title: " + getCharacterDataFromElement(line));

            }
    }

     public static String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
              CharacterData cd = (CharacterData) child;
              return cd.getData();
            }
            return "";
          }
}

You should read the following answer and work out the solution from that您应该阅读以下答案并从中找出解决方案

how-to-parse-xml-using-the-sax-parser 如何使用 sax 解析器解析 xml

I work on your query, and created parser class and calling class for solution.我处理您的查询,并创建了解析器 class 并调用 class 以获得解决方案。

XML Handler Class XML 处理器 Class

class xmlHandler extends DefaultHandler {
    private Vector nodes = new Vector();
    private Stack tagStack = new Stack();

    public void startDocument() throws SAXException {
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // System.out.println("1");
        if (qName.equals("clause")) {
            Noden node = new Noden();
            nodes.addElement(node);
            // System.out.println("2");
        }
        // System.out.println("3");
        tagStack.push(qName);
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String chars = new String(ch, start, length).trim();

        if (chars.length() > 0) {
            String qName = (String) tagStack.peek();
            Noden currentnode = (Noden) nodes.lastElement();
            // System.out.println(qName);

            if (qName.equals("en")) {
                currentnode.setEn(chars);
            } else if (qName.equals("alt")) {
                currentnode.setAlt(chars);
            }
        }
    }

    public void endElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        tagStack.pop();
    }

    public void endDocument() throws SAXException {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < nodes.size(); i++) {
            Noden currentnode = (Noden) nodes.elementAt(i);
            result.append("En : " + currentnode.getEn() + " Alt : "
                    + currentnode.getAlt() + "\n");
        }
        System.out.println(result.toString());
    }

    class Noden {
        private String en;
        private String alt;

        public Noden() {
        }

        public void setEn(String en) {
            this.en = en;
        }

        public void setAlt(String alt) {
            this.alt = alt;
        }

        public String getEn() {
            return en;
        }

        public String getAlt() {
            return alt;
        }
    };

and Calling Function调用 Function

try
        {
          SAXParserFactory factory = SAXParserFactory.newInstance();
          SAXParser saxParser = factory.newSAXParser();
          InputStream is = null;

          String xml = "<![CDATA[<translation>"+
          "<clause keyword=\"Alternative\"><en>Alternative</en><alt>Alternative</alt></clause>"+
          "<clause keyword=\"Back\"><en>Back</en><alt>Back</alt></clause>"+
          "<clause keyword=\"BackgroundImage\"><en>Bg. Image</en><alt>Bg. Image</alt></clause>"+
          "<clause keyword=\"ButtonColor\"><en>Button Color</en><alt>Button Color</alt></clause>"+
          "<clause keyword=\"ButtonText\"><en>Button Text</en><alt>Button Text</alt></clause>"+
          "<clause keyword=\"CategoryId\"><en>Category Id</en><alt>Category Id</alt></clause>"+
          "<clause keyword=\"English\"><en>English</en><alt>English</alt></clause>"+
          "<clause keyword=\"GsmNo\"><en>Gsm No</en><alt>Gsm No</alt></clause>"+
          "<clause keyword=\"GsmNumber\"><en>Gsm Number</en><alt>Gsm Number</alt></clause>"+
          "<clause keyword=\"LabelColor\"><en>Label Color</en><alt>Label Color</alt></clause>"+
          "<clause keyword=\"Language\"><en>Language</en><alt>Language</alt></clause>"+
          "<clause keyword=\"LanguageId\"><en>Lang Id</en><alt>Lang Id</alt></clause>"+
          "<clause keyword=\"Password\"><en>Password</en><alt>Password</alt></clause>"+
          "<clause keyword=\"PosSetup\"><en>Pos Setup</en><alt>Pos Setup</alt></clause>"+
         "<clause keyword=\"Redemption\"><en>Redemption</en><alt>Redemption</alt></clause>"+
          "<clause keyword=\"RedemptionSetup\"><en>Redemption Setup</en><alt>Redemption Setup</alt></clause>"+
          "<clause keyword=\"Sale\"><en>Sale</en><alt>Sale</alt></clause>"+
          "<clause keyword=\"Save\"><en>Save</en><alt>Save</alt></clause>"+
          "<clause keyword=\"ServiceUrl\"><en>Service Url</en><alt>Service Url</alt></clause>"+
          "<clause keyword=\"Setup\"><en>Setup</en><alt>Setup</alt></clause>"+
          "<clause keyword=\"Submit\"><en>Submit</en><alt>Submit</alt></clause>"+
          "<clause keyword=\"TerminalId\"><en>Terminal Id</en><alt>Terminal Id</alt></clause>"+
          "<clause keyword=\"TransactionId\"><en>Transaction Id</en><alt>Transaction Id</alt></clause>"+
          "<clause keyword=\"Void\"><en>Void</en><alt>Void</alt></clause>"+
          "<clause keyword=\"Voucher\"><en>Voucher</en><alt>Voucher</alt></clause>"+
          "<clause keyword=\"VoucherId\"><en>Voucher Id</en><alt>Voucher Id</alt></clause>"+
          " </translation>]]>";

          String newXml = xml.substring(xml.indexOf("<translation>"), xml.indexOf("]]"));         
          System.out.println(newXml);
          is = new ByteArrayInputStream(newXml.getBytes());
          InputSource inputSource = new InputSource(is);
          saxParser.parse(inputSource,new xmlHandler());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }

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

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