如何使用java在xml标记内使用属性值返回标记名称

时间:2016-03-11 05:21:24

标签: java xml

我需要使用Java代码返回 TAG名称。我的XML文件中有一个标记名称Interaction ,它有一个名为id的属性名称。我用来给程序中的id值或硬代码。 示例:字符串ID =" 244_choice_list_12&#34 ;; 我需要返回标记名称。 标记名称:互动。不使用Xpath

package com.video.convertor;
import java.io.File;
import java.io.IOException;
//import java.util.ArrayList;

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

public static void main(String[] args) 
throws IOException, ParserConfigurationException, SAXException {
    File xmlFile = new File("/Users/myXml/Sample.xml");
    DocumentBuilderFactory   dbFactory =  DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;

    dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);
    doc.getDocumentElement().normalize();

    walkNode(doc);
}

private static void walkNode(Node node) {
    NodeList nodeList = node.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
        checkChildNode(nodeList.item(i));
    }
}

private static void checkChildNode(Node node) {
    if (node.hasChildNodes()) {
        checkAttributes(node);

        walkNode(node);
    }
}
private static void checkAttributes(Node node) {
    if (node.hasAttributes()) {
        NamedNodeMap attributes = node.getAttributes();

        printAttributes(attributes);
    }
}

private static void printAttributes(NamedNodeMap attributes) {

    for (int i = 0; i < attributes.getLength(); i++) {
       Node attribute = attributes.item(i);
       if (attribute.getNodeName() == "id") {
       //System.out.println("Attribute found: " +  attribute.getNodeName()+ " : " + attribute.getNodeValue());
       String x = attribute.getNodeValue();
       String attr="244_choice_list_12";
       if(attr.equals(x)){
           //Node tag = attribute.getNodeName();
            System.out.println("Tag found :"+ "\t"+ x.);

        }else{
            System.out.println("There No such as Tag");
        }
      /*for(int j = 0;j < x.length();j++){ 
       if(attr.equals(x)){
           Node tag = attribute.getParentNode();
            System.out.println("Tag found :"+ "\t"+ tag);

        }else{
            System.out.println("There No such as Tag");
        }
      }*/
        //String 
       // String Value1 = attribute.getAttributes().getNamedItem("id").getNodeValue();
        //System.out.println("Attribute found: " +attribute.getNamedItem("id") + " : "+ attribute.getNodeName() + " : " + attribute.getNodeValue()));
        //System.out.println("Attribute:" +Value1 );
        }
        }

}}
xml File:
<itemBody class="etsmcm01fmt" id="244_item_content_3">
<rubric class="item_response_information " id="244_item_response_information_21" use="instruction" view="author proctor scorer testConstructor tutor"/>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../Passage/205.qti.xml"/>
<div class="stimulus_reference " id="244_stimulus_reference_4">
    <p class="introduction passage-intro " id="244_introduction_5">Read<span class="formatted_text text_decoration:underline " id="200244_formatted_text_6">two</span> sentences</p>
</div>
<Interaction class="choice_list " id="244_choice_list_12" maxChoices="4" minChoices="0" responseIdentifier="RESPONSE" shuffle="false">
    <prompt id="244_item_stem_8">
        <p class="stem_paragraph " id="244_stem_paragraph_9">story</p>
    </prompt>
    <simpleChoice class="block_choice " id="200244_block_choice_13" identifier="i1">
        <p class="choice_paragraph " id="200244_choice_paragraph_14">North and south</p>
    </simpleChoice>
    <simpleChoice class="block_choice " id="200244_block_choice_15" identifier="i2">
        <p class="choice_paragraph " id="200244_choice_paragraph_16">Sun and Moon</p>
    </simpleChoice>
    <simpleChoice class="block_choice " id="200244_block_choice_17" identifier="i3">
        <p class="choice_paragraph " id="200244_choice_paragraph_18">uncomfortable.</p>
    </simpleChoice>
    <simpleChoice class="block_choice " id="200244_block_choice_19" identifier="i4">
        <p class="choice_paragraph " id="200244_choice_paragraph_20">head.</p>
    </simpleChoice>
</Interaction></itemBody>

2 个答案:

答案 0 :(得分:1)

这是访问该文档的另一种方式。

function loadXMLDocument(url){
     var xmlHttpRequest = new xmlHttpRequest();
     xmlHttpRequest.open("get", url, false);
     xmlHttpRequest.send(null);
     var doc = xmlHttpRequest.responseXML;
     findTagMatchingId(doc);
}

使用它来获取节点。 Html Vs XML DOM是不同的。除了一些小事之外,这些命令实际上是相同的。

 doc.childNodes

然后在找到匹配的ID后获取元素的标记。

var x = document.getElementById("myP").tagName;

答案 1 :(得分:1)

最好使用正确的XPath表达式。手动遍历XML不是办法。通过在所有行上遍历游标,您不会在数据库表中查找值,是吗?不,您可以编写SQL查询来查找所需的行。

XML也是如此。您可以编写正确的XPath表达式或XQuery。您想要的XPath表达式将是简单的//*[@id='244_choice_list_12']

在XPath上查找一个很好的教程。 This one from w3schools是个好人。然后研究如何在Java中使用它。

您的XML和查询示例:

import java.io.StringReader;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

public class XPathTags {
    private static String xml=
"<itemBody class='etsmcm01fmt' id='244_item_content_3'>"+
"<rubric class='item_response_information ' id='244_item_response_information_21' use='instruction' view='author proctor scorer testConstructor tutor'/>"+
"<xi:include xmlns:xi='http://www.w3.org/2001/XInclude' href='../Passage/205.qti.xml'/>"+
"<div class='stimulus_reference ' id='244_stimulus_reference_4'>"+
"    <p class='introduction passage-intro ' id='244_introduction_5'>Read<span class='formatted_text text_decoration:underline ' id='200244_formatted_text_6'>two</span> sentences</p>"+
"</div>"+
"<Interaction class='choice_list ' id='244_choice_list_12' maxChoices='4' minChoices='0' responseIdentifier='RESPONSE' shuffle='false'>"+
"    <prompt id='244_item_stem_8'>"+
"        <p class='stem_paragraph ' id='244_stem_paragraph_9'>story</p>"+
"    </prompt>"+
"    <simpleChoice class='block_choice ' id='200244_block_choice_13' identifier='i1'>"+
"        <p class='choice_paragraph ' id='200244_choice_paragraph_14'>North and south</p>"+
"    </simpleChoice>"+
"    <simpleChoice class='block_choice ' id='200244_block_choice_15' identifier='i2'>"+
"        <p class='choice_paragraph ' id='200244_choice_paragraph_16'>Sun and Moon</p>"+
"    </simpleChoice>"+
"    <simpleChoice class='block_choice ' id='200244_block_choice_17' identifier='i3'>"+
"        <p class='choice_paragraph ' id='200244_choice_paragraph_18'>uncomfortable.</p>"+
"    </simpleChoice>"+
"    <simpleChoice class='block_choice ' id='200244_block_choice_19' identifier='i4'>"+
"        <p class='choice_paragraph ' id='200244_choice_paragraph_20'>head.</p>"+
"    </simpleChoice>"+
"</Interaction></itemBody>";

    private static String xpathExpr=
"//*[@id='244_choice_list_12']";

    public static void main(String[] args) {
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xpath.compile(xpathExpr);
            NodeList nodeList = (NodeList) expr.evaluate(new InputSource(new StringReader(xml)),XPathConstants.NODESET);
            for( int i = 0; i != nodeList.getLength(); ++i ) {
                System.out.println(nodeList.item(i).getNodeName());
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }
}

结果:Interaction