草庐IT

java - XML 获取所有同名节点

coder 2024-07-02 原文

我有如下所示的 xml 文档:

<?xml version="1.0"?>
<root>
    <success>true</success>
    <note>
        <note_id>32219</note_id>
        <the_date>1336763490</the_date>
        <member_id>108649</member_id>
        <area>6</area>
        <note>Note 123123123</note>
    </note>
    <note>
        <note_id>33734</note_id>
        <the_date>1339003652</the_date>
        <member_id>108649</member_id>
        <area>1</area>
        <note>This is another note.</note>
    </note>
    <note>
        <note_id>49617</note_id>
        <the_date>1343050791</the_date>
        <member_id>108649</member_id>
        <area>1</area>
        <note>this is a 3rd note.</note>
    </note>
</root>

我想拿走那份文件,并得到所有 <note>标签并将它们转换为字符串,然后将它们传递给我的 XML 类并将 XML 类放入数组列表中。我希望这是有道理的。所以这是我试图用来获取所有 <note> 的方法标签。

public ArrayList<XML> getNodes(String root, String name){
    ArrayList<XML> elList = new ArrayList<>();
    NodeList nodes = doc.getElementsByTagName(root);
    for(int i = 0; i < nodes.getLength(); i++){
        Element element = (Element)nodes.item(i);
        NodeList nl = element.getElementsByTagName(name);
        for(int c = 0; c < nl.getLength(); c++){
            Element e = (Element)nl.item(c);
            String xmlStr = this.nodeToString(e);
            XML xml = new XML();
            xml.parse(xmlStr);
            elList.add(xml);
        }
    }
    return elList;
}

private String nodeToString(Node node){
    StringWriter sw = new StringWriter();
    try{
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), new StreamResult(sw));
    }catch(TransformerException te){
        System.out.println("nodeToString Transformer Exception");
    }
    return sw.toString();
}

所以,我的问题是,我怎样才能得到每个 <note>标记为字符串?使用我现在所有的代码,我得到的是null对于 String xmlStr = e.getNodeValue(); .

编辑
我编辑了我的主要代码,这似乎有效。

最佳答案

澄清后更新

您可以找到所有 <note>使用 XPath 的元素。

这将使您能够简单地隔离每个节点。然后,您可以根据找到的节点创建一个新文档并将其转换回字符串

public class TestXML01 {

    public static void main(String[] args) {

        String xml = "<?xml version=\"1.0\"?>";
        xml += "<root>";
        xml += "<success>true</success>";
        xml += "<note>";
        xml += "<note_id>32219</note_id>";
        xml += "<the_date>1336763490</the_date>";
        xml += "<member_id>108649</member_id>";
        xml += "<area>6</area>";
        xml += "<note>Note 123123123</note>";
        xml += "</note>";
        xml += "<note>";
        xml += "<note_id>33734</note_id>";
        xml += "<the_date>1339003652</the_date>";
        xml += "<member_id>108649</member_id>";
        xml += "<area>1</area>";
        xml += "<note>This is another note.</note>";
        xml += "</note>";
        xml += "<note>";
        xml += "<note_id>49617</note_id>";
        xml += "<the_date>1343050791</the_date>";
        xml += "<member_id>108649</member_id>";
        xml += "<area>1</area>";
        xml += "<note>this is a 3rd note.</note>";
        xml += "</note>";
        xml += "</root>";

        ByteArrayInputStream bais = null;

        try {
            bais = new ByteArrayInputStream(xml.getBytes());
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document xmlDoc = builder.parse(bais);

            Node root = xmlDoc.getDocumentElement();

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xPath = xFactory.newXPath();

            XPathExpression xExpress = xPath.compile("/root/note");
            NodeList nodes = (NodeList) xExpress.evaluate(root, XPathConstants.NODESET);

            System.out.println("Found " + nodes.getLength() + " note nodes");

            for (int index = 0; index < nodes.getLength(); index++) {
                Node node = nodes.item(index);
                Document childDoc = builder.newDocument();
                childDoc.adoptNode(node);
                childDoc.appendChild(node);
                System.out.println(toString(childDoc));
            }

        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            try {
                bais.close();
            } catch (Exception e) {
            }
        }
    }

    public static String toString(Document doc) {

        String sValue = null;

        ByteArrayOutputStream baos = null;
        OutputStreamWriter osw = null;

        try {
            baos = new ByteArrayOutputStream();
            osw = new OutputStreamWriter(baos);

            Transformer tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.setOutputProperty(OutputKeys.METHOD, "xml");
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            DOMSource domSource = new DOMSource(doc);
            StreamResult sr = new StreamResult(osw);
            tf.transform(domSource, sr);

            osw.flush();
            baos.flush();
            sValue = new String(baos.toByteArray());
        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            try {
                osw.close();
            } catch (Exception exp) {
            }
            try {
                baos.close();
            } catch (Exception exp) {
            }
        }
        return sValue;
    }
}

现在输出...

Found 3 note nodes
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
    <note_id>32219</note_id>
    <the_date>1336763490</the_date>
    <member_id>108649</member_id>
    <area>6</area>
    <note>Note 123123123</note>
</note>

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
    <note_id>33734</note_id>
    <the_date>1339003652</the_date>
    <member_id>108649</member_id>
    <area>1</area>
    <note>This is another note.</note>
</note>

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
    <note_id>49617</note_id>
    <the_date>1343050791</the_date>
    <member_id>108649</member_id>
    <area>1</area>
    <note>this is a 3rd note.</note>
</note>

关于java - XML 获取所有同名节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447960/

有关java - XML 获取所有同名节点的更多相关文章

  1. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  5. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  6. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  7. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  8. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  9. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  10. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

随机推荐