Link to home
Start Free TrialLog in
Avatar of trevorhigbee2000
trevorhigbee2000

asked on

Transform XML JDOM to String

I have a program in which I've created a JDOM document with various elements.  I want to take the JDOM Document and extract the stuff inside the element tags ( these things <>) as a string.  Any suggestions?

I don't know if I need to use the JDOM transformer or the javax.xml transformer.  I don't know how to use either one.  Any help would be fantastic.

Here's some of my code:

Document xml;

Element root = new ELement("Login");
Document doc = new Document(root);
root.setTExt(xml);

I'm getting this when I print the document to the console:
<Login>myName</Login>

I need to get myName in a string format.
Avatar of MogalManic
MogalManic
Flag of United States of America image

You can either taverse the JDOM document or write a XSL stylesheet.  Traversal should be easier
  Element loginElement=(Element)doc.getChild("Login");
  String loginValue =  loginElement.getText();


To use the transformer, I would suggest using the JAXP API.  It will work if you decide to use the W3C DOM with no changes:

   StreamSource xslSource=new StreamSource(new File("getLogin.xsl"));
   Transformer t=TransformerFactory.newInstance().newTransformer(xslSource);

   Source xmlSource=new JDOMSource(doc);
   Result out=new StreamResult(System.out);
   t.transform(xmlSource, out);

****
getLogin.xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:template match='/'>
          <xsl:value-of select='//Login'/>
    </xsl:template>
</xsl:stylesheet>

Avatar of trevorhigbee2000
trevorhigbee2000

ASKER

When I do:

Element loginElement=(Element)doc.getChild("Login");

I get an error:
"The method getChild(String) is undefined for the type Document."
ASKER CERTIFIED SOLUTION
Avatar of CodingExperts
CodingExperts

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial