Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sax XML Parser, parsing custom "values" within XML tags?

I haven't worked much with XML before so maybe my ignorance on proper terminology is hurting me in my searches on how to do this. I have the code snippet below which I am using to parse an XML file like the one below. The problem is that it only picks up XML values within <Tag>Value</Tag> but not for the one below where I need to get the value of TagValue, which in this case would be "Russell Diamond".

I would appreciate if anyone can offer assistance as to how to get custom values like this. Thanks.

<Tag TagName="#Subject" TagDataType="Text" TagValue="Russell Diamond"/>

The snippet I am using:

public void printElementNames(String fileName) throws IOException {
    //test write to file
       FileWriter fstream = new FileWriter("/home/user/Desktop/readEDRMtest.txt");
        final BufferedWriter out = new BufferedWriter(fstream);


    //

    try {
        SAXParserFactory parserFact = SAXParserFactory.newInstance();
        SAXParser parser = parserFact.newSAXParser();
        System.out.println("XML Elements: ");
        DefaultHandler handler = new DefaultHandler() {
            public void startElement(String uri, String lName, String ele,
                    Attributes attributes) throws SAXException {
                // print elements of xml
                System.out.println(ele);
                try {
                    out.write(ele);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

             public void characters(char ch[], int start, int length)
             throws SAXException {


                System.out.println("Value : "
                    + new String(ch, start, length));
                try {
                    out.write("Value : "
                            + new String(ch, start, length));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        };
like image 564
Rick Avatar asked Feb 05 '26 08:02

Rick


1 Answers

You want to look into extracting attributes. Search on that and you'll find your answer.

The DefaultHandler class's startElement(...) method passes a parameter called attributes that refers to an Attribute object. The API for the Attribute interface will describe how to extract the information you need from this object.

For example:

out.write(attributes.getValue("TagValue"));
like image 92
Hovercraft Full Of Eels Avatar answered Feb 07 '26 22:02

Hovercraft Full Of Eels