简体   繁体   中英

How we can tracking attribute of XML

I have xml

<schemans2:ServicepointForAccountRow AccountID="123456" ServicePointID="987654"
                                 LongDescription="TE Fix Network RES SINGLE PHS/TEP 13 MR/FN TEP Rt 0010/3220 W INA RD, 13203, TUCSON, AZ, 85741-2169, TEP"
                                 UsageInfo="Add"/>

I want one element ServicePointID.

How we can tracking attribute event for the SERVICEPOINTFORACCOUNTROW tag using case XMLStreamConstants.ATTRIBUTE

Here is the code

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Parser;

public class Test {

    public static void main(String[] args) {
        String xml = "<schemans2:ServicepointForAccountRow AccountID=\"123456\" ServicePointID=\"987654\" LongDescription=\"TE Fix Network RES SINGLE PHS/TEP 13 MR/FN TEP Rt 0010/3220 W INA RD, 13203, TUCSON, AZ, 85741-2169, TEP\" UsageInfo=\"Add\" />";
        Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
        List<Node> nodes = doc.childNodes();
        for(Node n : nodes) {
            System.out.println(n.attr("ServicePointID"));
        }
    }
}

Output

987654

Since you mention of using XMLStreamConstants , i am assuming you plan to use XMLStreaming interfaces. One way of doing that is as follows

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader parser = factory.createXMLStreamReader(new StringReader(xml));
    while (parser.hasNext()){
                int event = parser.next();
                    if (event == XMLStreamConstants.START_ELEMENT){
                        if (parser.getLocalName().equals("schema")){
                            String servicePointID = parser.getAttributeValue(null, "ServicePointID");
                        if (servicePointID != null)
                            System.out.println(servicePointID);
            }

Note that the XML thing is not getting reported in a stream/event based interface and hence i had to catch it using START ELEMENT and manipulate that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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