簡體   English   中英

在Java中以字符串形式讀取XML

[英]Reading XML as string in Java

有人可以幫我這個忙。 我想知道如何將此示例讀取為字符串? 我知道如何閱讀第一個,但不知道全部閱讀

<Tr rn=\"000000000000000\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2000-01-01\" dOdprt=\"2000-01-01\" iban=\"SI00\" eno=\"R\" vir=\"B\" maticnaPps=\"0000000000\"><Imetnik davcna=\"00000000\" matSub=\"0000000000\" drz=\"705\"><PopolnoIme>UNKNOWN</PopolnoIme><KratkoIme>UNKNOWN</KratkoIme><Naslov sifTipNaslova=\"00\" sifObcina=\"000\" sifPosta=\"0000\" sifUlica=\"0000\" sifNaselje=\"000\" stHisna=\"000\" sifHsmid=\"00000000\"><Obcina>UNKNOWN</Obcina><Posta>UNKNOWN</Posta><Ulica>UNKNOWN</Ulica><Naselje>UNKNOWN</Naselje></Naslov></Imetnik></Tr>

也許這就是您想要的? 此處的示例: http : //ideone.com/N4jIO

import java.io.ByteArrayInputStream;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Main {

    public static void main(String... args) throws IOException, SAXException, ParserConfigurationException {

        String xml = "<Tr rn=\"000000000000000\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2000-01-01\" dOdprt=\"2000-01-01\" iban=\"SI00\" eno=\"R\" vir=\"B\" maticnaPps=\"0000000000\"><Imetnik davcna=\"00000000\" matSub=\"0000000000\" drz=\"705\"><PopolnoIme>UNKNOWN</PopolnoIme><KratkoIme>UNKNOWN</KratkoIme><Naslov sifTipNaslova=\"00\" sifObcina=\"000\" sifPosta=\"0000\" sifUlica=\"0000\" sifNaselje=\"000\" stHisna=\"000\" sifHsmid=\"00000000\"><Obcina>UNKNOWN</Obcina><Posta>UNKNOWN</Posta><Ulica>UNKNOWN</Ulica><Naselje>UNKNOWN</Naselje></Naslov></Imetnik></Tr>";

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));

        print(doc.getDocumentElement(), "");
    }

    private static void print(Node e, String tab) {

        if (e.getNodeType() == Node.TEXT_NODE) {
            System.out.println(tab + e.getNodeValue());
            return;
        }


        System.out.print(tab + e.getNodeName());

        NamedNodeMap as = e.getAttributes();
        if (as != null && as.getLength() > 0) {
            System.out.print(" attributes=[");
            for (int i = 0; i < as.getLength(); i++) 
                System.out.print((i == 0 ? "" : ", ") + as.item(i));
            System.out.print("]");
        }
        System.out.println();

        if (e.getNodeValue() != null)
            System.out.println(tab + " " + e.getNodeValue());

        NodeList childs = e.getChildNodes();
        for (int i = 0; i < childs.getLength(); i++)
            print(childs.item(i), tab + " ");
    }
}

如果您的目標是從String對象加載/解析XML文檔,則只需要使用常規的XML文檔加載代碼,而是使用StringReader提供輸入流。 (或ByteArrayInputStream或其他任何東西,只要您構建了一系列轉換就可以作為InputStream來訪問數據)。

下面是一個示例(未經測試且沒有異常處理。很抱歉,我目前沒有測試環境):

  final DocumentBuilderFactory f  = DocumentBuilderFactory.newInstance();
  final DocumentBuilder        db = f.newDocumentBuilder();
  final InputSource            is = new InputSource();

  is.setCharacterStream(new StringReader(YOURSTRING));
  final Document               doc = db.parse(is);

  doc.getDocumentElement().normalize();
  /*
   * do whatever you want/need here.
   */

如果那不是您想要的,抱歉,我不太確定您在這里問的是什么。

使用xerces可能更容易理解:

public static void loadImetniks(String filePath) {

        File xmlFile;

        SAXBuilder builder;

        Element root, child;

        Imetnik imet;//another class that you have to create to help you for parsing

        Document doc;

        try {

            xmlFile = new File(filePath);

            builder = new SAXBuilder();  // parameters control validation, etc

            doc = builder.build(xmlFile);



            root = doc.getRootElement(); // Tr could be the root but I am not sure if you will have more Tr nodes in the same file?? 

            tr.setRn(root.getAttributeValue(Constants.RN));//define the constants string in another file
            tr.setVr(root.getAttributeValue(Constants.VR));
            tr.setSspre(root.getAttributeValue(Constants.SSPRE));
            tr.setReg(root.getAttributeValue(Constants.REG));
            tr.setIban(root.getAttributeValue(Constants.IBAN));
        .... //repeat for every attribute
        ....



            List children = root.getChildren(); // depends of how many Imetnik you will have

            for (Iterator iter = children.iterator(); iter.hasNext();) {

                child = (Element) iter.next();

                imet = new Imetnik();

                imet.loadXML(child); // you have to define the loadXML function in your object Imetnik which should extract the attributes and internal nodes

                //imets.add(contest); // just use in the case that you will have to extract more than one Imetnik node

            }



        } catch (Exception e) {

            log.error("Error al hacer el parsing del contests.xml!");

            log.error(e.getMessage());

        }

    }

例如,您的Imetnik類應包含:

   public void loadXML(Element root) {

        Element child;

    //Naslov naslov;  // for Naslov because it could be an object itself


        davcna = root.getAttributeValue(Constants.DAVCNA); //define the string constant
        matSub = root.getAttributeValue(Constants.MATSUB); //define the string constant
        drz = Integer.parseInt(root.getAttributeValue(Constants.DRZ)); //define the string constant



        List children = root.getChildren(); // your root is Imetnik now

        for (Iterator iter = children.iterator(); iter.hasNext();) {
          .....
          .......
       }
}

解析Java中XML文件的最佳解決方案是使用專用的庫,例如:

  1. 的Xerces
  2. 薩克斯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM