【问题标题】:Reading XML as string in Java在 Java 中将 XML 读取为字符串
【发布时间】:2011-04-24 03:59:16
【问题描述】:

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

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

【问题讨论】:

  • “读取为字符串”是什么意思?如“此内容在 .xml 文件中,我想使用 java 读取它并将其放入字符串中”?顺便说一句,看起来像示例本身,所有的`\"`都是java字符串
  • 你想把xml读成字符串还是Tr元素的属性值读成字符串?
  • 我认为他/她的意思是从 String 对象解析 XML 文档。
  • 在这种情况下,它是stackoverflow.com/questions/729621/…的副本
  • 归根结底,您真正需要的只是Document document = builder.parse(new InputSource(new StringReader(xmlString)));

标签: java xml string


【解决方案1】:

也许这就是您要找的东西?此处示例: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 + " ");
    }
}

【讨论】:

  • 非常接近,是的。我会尝试从头开始复制/粘贴输出,看看输出应该是什么格式。 rn = 031001002126306
  • 我只是不知道如何从头开始阅读整个内容。
【解决方案2】:

如果您的目标是从 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.
   */

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      1. Xerces
      2. Sax

      【讨论】:

      • 我放了 \" 这样java就不会把它算作注释。是的,我想把这一行读成字符串。
      • 不是一个很有帮助的答案。也许您提供了一些代码来让 OP 运行。或者指向一个好的教程。
      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      相关资源
      最近更新 更多