简体   繁体   English

在xml下面阅读的最简单,最好的方法是什么?

[英]What is the easy and best way to read below xml?

I am new to XML. 我是XML的新手。

Please let me know easy and best way to read xml below in java. 请让我知道以下在Java中读取xml的简便最佳方法。 In my xml, I have queries as root and query as child element in it. 在我的xml中,我将查询作为根,并将查询作为子元素。

<queries>
    <query id="getUserByName">
        select * from users where name=?
    </query>
    <query id="getUserByEmail">
        select * from users where email=?
    </query>
</queries>

I will pass query id, based on that we need to fetch corresponding query. 我将传递查询ID,基于此我们需要获取相应的查询。 Please help me with code for better understanding. 请帮助我提供代码以更好地理解。

With XPath, it's simple. 使用XPath,很简单。

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

public class Test {

  public static final String xml = 
    "<queries>"
    + "  <query id=\"getUserByName\">"
    + "    select * from users where name=?"
    + "  </query>"
    + "  <query id=\"getUserByEmail\">"
    + "    select * from users where email=?" 
    + "  </query>"
    + "</queries>"; 


  public static void main(String[] args) throws Exception {
    System.out.println(getQuery("getUserByName"));
    System.out.println(getQuery("getUserByEmail"));

  }

  public static String getQuery (String id) throws Exception {
    InputStream is = new ByteArrayInputStream(xml.getBytes("UTF8"));
    InputSource inputSource = new InputSource(is);
    XPath xpath = XPathFactory.newInstance().newXPath();
    return xpath.evaluate("/queries/query[@id='" + id +"']", inputSource);
  }
}

A very easy code to implement would be JAXB parser. JAXB解析器是一个非常容易实现的代码。 Personally I love this one as it establishes everything using simple annotations. 我个人很喜欢这一点,因为它可以使用简单的注释建立所有内容。

Steps. 脚步。

  1. Create a couple of bean classes with the structure of your xml. 用您的xml结构创建几个bean类。 In your case Queries class containing List<Query> . 在您的情况下,包含List<Query> Queries类。 Define Query to contain a string variable. 定义查询以包含一个字符串变量。 If you take the time to go through the annotations, I'm sure you can do this even with a single bean class but with multiple annotations. 如果您花时间浏览批注,那么即使使用单个bean类但具有多个批注,我相信您也可以做到这一点。

  2. Pass your string of XML to a JAXB context of Queries class and you are done. 将您的XML字符串传递到Queries类的JAXB上下文中,您就完成了。

  3. You'll get one Java object for each Query tag. 您将为每个Query标签获得一个Java对象。 Once you get the bean class, manipulation becomes easy. 一旦获得bean类,操作就变得容易了。

Ref: 参考:

JAXB Hello World Example JAXB Hello World示例

JAXB Tutorial JAXB教程

A good solution would be to load these queries to a map first and access it later based on the map. 一个好的解决方案是先将这些查询加载到地图上,然后再根据地图进行访问。 To load queries to a map you could do something like: 要将查询加载到地图,您可以执行以下操作:

Map<String, String> queriesMap = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream inputStream = new ByteArrayInputStream("<queries>    <query id=\"getUserByName\">        select * from users where name=?    </query>    <query id=\"getUserByEmail\">        select * from users where email=?    </query></queries>".getBytes());
// you could use something like: new FileInputStream("queries.xml");

Document doc = documentBuilder.parse(inputStream);

// get queries elements
NodeList queriesNodes = doc.getElementsByTagName("queries");

// iterate over it
for (int i = 0; i < queriesNodes.getLength(); i++) {

    // get queries element
    Node node = queriesNodes.item(i);

    // get query elements (theoretically)
    NodeList queryNodes = node.getChildNodes();
    for (int j = 0; j < queryNodes.getLength(); j++) {
        Node queryNode = queryNodes.item(j);

        // if not element just skip to next one (in case of text nodes for the white spaces)
        if (!(queryNode.getNodeType() == Node.ELEMENT_NODE)) {
            continue;
        }
        // get query
        Node idAttr = queryNode.getAttributes().getNamedItem("id");

        if (idAttr != null) {
            queriesMap.put(idAttr.getTextContent(), StringUtils.trim(queryNode.getTextContent()));
        }
    }
}

System.out.println(queriesMap);

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

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