在 Java 中将 XML 作为字符串读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3912382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:56:56  来源:igfitidea点击:

Reading XML as string in Java

javaxmlstring

提问by Igor

Could somebody help me with this. I would like to know how to read this example as string? I know how to read first one but don't know how to read them all

有人可以帮我解决这个问题。我想知道如何将这个例子读为字符串?我知道如何阅读第一个但不知道如何阅读所有内容

<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>

采纳答案by dacwe

Maybe this is what you are looking for? Example here: http://ideone.com/N4jIO

也许这就是你要找的?这里的例子: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 + " ");
    }
}

回答by haylem

If your goal is to load/parse an XML Document from a String object, you'll simply need to use the usual XML document loading code, but to use a StringReaderto provide your inputstream. (or a ByteArrayInputStream, or anything really as long as you build up a chain of transformations that lets your access your data as an InputStream).

如果您的目标是从 String 对象加载/解析 XML 文档,则只需使用通常的 XML 文档加载代码,但要使用StringReader来提供输入流。(或一个 ByteArrayInputStream,或者任何真正的东西,只要你建立了一个转换链,让你以 InputStream 的形式访问你的数据)。

An example follows here (untested and without exception handling. Sorry, I don't have a test environment at the moment):

下面是一个示例(未经测试且没有异常处理。抱歉,我目前没有测试环境):

  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.
   */

If that's not what you wanted, sorry I am not quite sure what you were asking here.

如果这不是您想要的,抱歉,我不太确定您在这里问的是什么。

回答by Nervo Verdezoto

Using xerces could be more understandable:

使用 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());

        }

    }

For instance, your Imetnik class should contain:

例如,您的 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();) {
          .....
          .......
       }
}

回答by Manuel Selva

The best solution to parse XML files in Java is to use a dedicated library such as:

在 Java 中解析 XML 文件的最佳解决方案是使用专用库,例如​​:

  1. Xerces
  2. Sax
  1. 塞尔西斯
  2. 萨克斯