• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 793
  • Last Modified:

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.
0
trevorhigbee2000
Asked:
trevorhigbee2000
1 Solution
 
MogalManicCommented:
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>

0
 
trevorhigbee2000Author Commented:
When I do:

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

I get an error:
"The method getChild(String) is undefined for the type Document."
0
 
CodingExpertsCommented:
trevor,

you first need to get the element (node) from the document, then only you can access the individual properties and/or child nodes.  so do this...

Element root = doc.getRootElement();
String childText = root.getChildText( "Login" );

best,
-CodingExperts
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now