XML in Java

Is there an API to create xml document content or may be the xml format? I can do the same by using a StringBuffer and embedding my content between the custom tags.
If possible I am looking for an elegant way to do the same, may be adding nodes to a tee and appending children to the same. I appreciate if someone can provide me a hint.
~SirG

Try JDom:
www.jdom.org
%

Similar Messages

  • Generating XML Using JAVA

    How to generate XML usng java without using following.
    import org.apache.xerces.dom.DocumentImpl;
    import org.apache.xml.serialize.OutputFormat;
    import org.apache.xml.serialize.XMLSerializer;
    XML to be generated is as follows.
    <?xml version="1.0" encoding="UTF-8"?>
    <Modi xmlns:xsi="Modi/Modi1">
    <docConfig>
    <className>PO</className>
    <classDesc>Purchase</classDesc>
    <create>Y</create>
    </docConfig>
    <indexConfig>
    <index sequence="1">
    <shortName>PODATE</shortName>
    <displayName>PO Date</displayName>
    <type>date</type>
    <length>10</length>
    </index>
    </indexConfig>
    </upload>

    Two answers.
    If you want to not use any of the XML-oriented classes, you can use a PrintWriter. Just code:
    PrintWriter pw = new PrinteWriter(whatever);
    pw.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
    etc.If you want to use XML-oriented classes, but just not these 3 (can't imagine why), then use
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    instead of XMLSerializer and OutputFormat, and
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    instead of the DocumentImpl
    Dave Patterson

  • How to get previous tag name from a xml in java

    Hai
          I need to get the previous tag name from a xml in java.
         I got the current tagname , i need to get the previous tagname
        NodeList parentactionList = lParentRule.getElementsByTagName(
    "parentactiondetails");
    i use this way of getting the the current tag name, i need to get the previous tag name ie.. before "parentactiondetails"
    for sample
    </parentruledetails>
    </Parentrule>
    </SingleParentRule>
    <parentactiondetails ACTION_FLAG="RulePass" PARENT_RULE_CODE="PR626"/>
    <ParentCompliance>
    i have xml like this i am getting the "parentactiondetails " ...  now i need to get the previous tag name </SingleParentRule> in java
    Can any one help me,

    still i am not able to get the correct value...
    i used the way wat u said it is not even going inside the if condition
    below is my actual xml as before i asked i need the before tag name of <parentactiondetails>
    ie  the closing tag of </Singleparentrule>
    i have attached the xml also
    pl reply me as soon as possible
    <?xml version="1.0" encoding="UTF-8"?>
    <GRC>
    <ParentInventory>
    <Vendor comment="" createdBy="root" vendorCode="1001" vendorName="Cisco">
    <DeviceType createdBy="root" devTypeCode="1001" devTypeName="Router" vendorCode="1001">
    <Series createdBy="root" devTypeCode="1002" seriesCode="1110" seriesName="2800" vendorCode="1001">
    <Model createdBy="root" devTypeCode="1002" modelCode="1459" modelName="4506" seriesCode="1110" vendorCode="1001">
    <Sub createdBy="root" devTypeCode="1002" modelCode="1459" seriesCode="1110" subCode="1695" subName="CAT4500-SUP4" vendorCode="1001">
    <CodeVersion createdBy="root" devTypeCode="1002" modelCode="1459" seriesCode="1110" startCode="2207" startName="12.2(25)EWA2" subCode="1695" vendorCode="1001">
    <ImageName createdBy="root" devTypeCode="1002" endCode="5508" endName="Standard" modelCode="1459" seriesCode="1110" startCode="2207" subCode="1695" vendorCode="1001"/>
    </CodeVersion>
    <CodeVersion createdBy="root" devTypeCode="1002" modelCode="1459" seriesCode="1110" startCode="2225" startName="12.2(5)T" subCode="1695" vendorCode="1001"/>
    </Sub>
    </Model>
    </Series>
    </DeviceType>
    </Vendor>
    </ParentInventory>
    <Parentrule>
    <parentruledetails COMMENTS="1PARENT_RULEFILT_AUDITPASS" CREATED_BY="root" DEVICE_LEVEL_FLAG="Configuration" PARENT_RULE_CODE="PR626" PARENT_RULE_TYPE="SPR_AP" RULE_NAME="1PARENT_RULEFILT_AUDITPASS">
    <parentscope DEVICE_TYPE_NAME="Switch" END_CODE_VERNAME="Standard" MODEL_NAME="3750-24PS" PARENT_RULE_CODE="PR626" SERIES_NAME="3750" ST_CODE_VERNAME="12.2(25)SEE2" SUP_CPU_NAME="3750" VENDOR_NAME="Cisco"/>
    <parentmultiscope COLUMN_INDEX="0" DEVICE_TYPE_NAME="Switch" END_CODE_VERNAME="Standard" MODEL_NAME="3750-24PS" MULTI_SCOPE_CODE="{1=1001~1002~ 1010~ 1131~ 1190~ 2041~E~5255}" MULTI_SCOPE_NAME="{1=Cisco~Switch~3750~3750-24PS~3750~12.2(25)SEE2~E~Standard}" OPERATOR="E" PARENT_RULE_CODE="PR626" SERIES_NAME="3750" ST_CODE_VERNAME="12.2(25)SEE2" SUP_CPU_NAME="3750" VENDOR_NAME="Cisco"/>
    <SingleParentRule CHILD_TYPE="ALL" COLUMN_INDEX="0" FILT_CONDN="PA" PARENT_RULE_CODE="PR626" RULE_CODE="PR625[AND]," RULE_TYPE_FLAG="singleparentrule">
    <Parentrule>
    <parentruledetails COMMENTS="1CUSTRULE_PARENT_CROSSREF_FAIL" CREATED_BY="root" DEVICE_LEVEL_FLAG="Configuration" PARENT_RULE_CODE="PR625" PARENT_RULE_TYPE="PCR_CR" RULE_NAME="1CUSTRULE_PARENT_CROSSREF_FAIL">
    <parentscope DEVICE_TYPE_NAME="Switch" END_CODE_VERNAME="Standard" MODEL_NAME="3750-24PS" PARENT_RULE_CODE="PR625" SERIES_NAME="3750" ST_CODE_VERNAME="12.2(25)SEE2" SUP_CPU_NAME="3750" VENDOR_NAME="Cisco"/>
    <parentmultiscope COLUMN_INDEX="0" DEVICE_TYPE_NAME="Switch" END_CODE_VERNAME="Standard" MODEL_NAME="3750-24PS" MULTI_SCOPE_CODE="{1=1001~1002~ 1010~ 1131~ 1190~ 2041~E~5255}" MULTI_SCOPE_NAME="{1=Cisco~Switch~3750~3750-24PS~3750~12.2(25)SEE2~E~Standard}" OPERATOR="E" PARENT_RULE_CODE="PR625" SERIES_NAME="3750" ST_CODE_VERNAME="12.2(25)SEE2" SUP_CPU_NAME="3750" VENDOR_NAME="Cisco"/>
    <ParentCommand>
    <Command ChildType="Console" cmdCode="37135" cmdName="login authentication &lt;string&gt;"/>
    </ParentCommand>
    <parentcustomdetails CHILD_TYPE="Console" CMD_CODE="37135" CMD_NAME="login authentication [string]" CMD_OPTION="login authentication " COLUMN_INDEX="0" CONDN_OPER="exists" CONDN_VALUE="True" PARENT_RULE_CODE="PR625" RULE_TYPE_FLAG="Customrule"/>
    <parentcustomdetails CHILD_TYPE="Console" CMD_CODE="37135" CMD_NAME="login authentication [string]" CMD_OPTION="string" COLUMN_INDEX="1" CONDN_OPER="equalsto" CONDN_VALUE="cisco" PARENT_RULE_CODE="PR625" RULE_TYPE_FLAG="Customrule"/>
    <parentcustomconsole CHILD_TYPE="Console" CONSOLE_NUM="Any" PARENT_RULE_CODE="PR625"/>
    <parentactiondetails ACTION_FLAG="CrossRef" PARENT_RULE_CODE="PR625"/>
    <parentcrossrefdetails ACTION_FLAG="CrossRef" CHILD_TYPE="Console" CMD_CODE="37135" CMD_NAME="login authentication [string]" CMD_OPTION="login authentication " COLUMN_INDEX="0" CONDN_OPER="exists" CONDN_VALUE="True" PARENT_RULE_CODE="PR625"/>
    <parentcrossrefdetails ACTION_FLAG="CrossRef" CHILD_TYPE="Console" CMD_CODE="37135" CMD_NAME="login authentication [string]" CMD_OPTION="string" COLUMN_INDEX="1" CONDN_OPER="equalsto" CONDN_VALUE="AAAAAA" PARENT_RULE_CODE="PR625"/>
    <parentcrossrefconsole ACTION_FLAG="CrossRef" CHILD_TYPE="Console" CONSOLE_NUM="Any" PARENT_RULE_CODE="PR625"/>
    <ParentCompliance>
    <PRComp comments="Group Policy is an important and useful addition to your Active Directory deployment. Managing your internal network and ensuring compliance .Group Policies are a set of &quot;rules&quot; that are applied to different parts of a Windows-based network" compCode="1006" compName="INTERNAL GROUP POLICY" createdBy="root" url="http://www.INTERNAL GROUP POLICY.com"/>
    <PRComp comments="This is the compliance for the department of Security agency" compCode="1012" compName="DISA" createdBy="root" url="http://iase.disa.mil/stigs/checklist/"/>
    <PRComp comments="This is the compliance from the National Security Agency" compCode="1013" compName="NSA" createdBy="root" url="http://checklists.nist.gov/chklst_detail.cfm?confi"/>
    <PRComp comments="he Center for Internet Security (CIS) is a not-for-profit organization that helps enterprises reduce the risk of business and e-commerce disruptions resulting from inadequate technical security controls, and provides enterprises with resources for measuring information security status and making rational security investment decisions" compCode="1020" compName="CIS" createdBy="root" url="http://www.cisecurity.org/"/>
    <PRComp comments="This is a Cisco document. It outlines the key security elements identified for Network Security Baseline, along with implementation guidelines to assist in their design, integration, and deployment in production networks. " compCode="1022" compName="Cisco Secuirty Baseline" createdBy="root" url="http://www.cisco.com/en/US/docs/solutions/Enterpri"/>
    <PRComp comments="This is the best practices from industry experts to help make audit recommendations in a customers environment. " compCode="1023" compName="360 GRC Best Practice" createdBy="root" url="http://www.360grc.com"/>
    </ParentCompliance>
    <parentriskrecommendationdetails ACTION_FLAG="CrossRef" AUDIT_RESULTS="Both_pass_fail_result" CHILD_TYPE="ALL" CMD_CODE="fdg" COMMAND_REF="dfs" DEFINITION="dfgd" DEVICE_RECOM_CATEGORY_CODE="IP - Addressing Services" DEVICE_RISK_CATEGORY_CODE="IP - Addressing Services" DISP_LEVEL="Parent and child result" PARENT_RULE_CODE="PR625" RATING1="2" RATING1_NAME="DISA" RATING2="2" RATING2_NAME="NSA" RATING3="2" RATING3_NAME="Cisco Secuirty Baseline" RATING4="2" RATING4_NAME="CIS" RATING5="2" RATING5_NAME="360 GRC Best Practice" RATING6="2" RATING6_NAME="INTERNAL GROUP POLICY" RATING_IMPACT="Low" RATING_PRIORITY="Low" RATING_URGENCY="Low" RECOMENDATION="ss" WEB_REF="sfs" WEIGHTING1="10" WEIGHTING1_NAME="DISA" WEIGHTING2="10" WEIGHTING2_NAME="NSA" WEIGHTING3="10" WEIGHTING3_NAME="Cisco Secuirty Baseline" WEIGHTING4="10" WEIGHTING4_NAME="CIS" WEIGHTING5="10" WEIGHTING5_NAME="360 GRC Best Practice" WEIGHTING6="10" WEIGHTING6_NAME="INTERNAL GROUP POLICY"/>
    </parentruledetails>
    </Parentrule>
    </SingleParentRule>
    <parentactiondetails ACTION_FLAG="RulePass" PARENT_RULE_CODE="PR626"/>
    <ParentCompliance>
    <PRComp comments="Group Policy is an important and useful addition to your Active Directory deployment. Managing your internal network and ensuring compliance .Group Policies are a set of &quot;rules&quot; that are applied to different parts of a Windows-based network" compCode="1006" compName="INTERNAL GROUP POLICY" createdBy="root" url="http://www.INTERNAL GROUP POLICY.com"/>
    <PRComp comments="This is the compliance for the department of Security agency" compCode="1012" compName="DISA" createdBy="root" url="http://iase.disa.mil/stigs/checklist/"/>
    <PRComp comments="This is the compliance from the National Security Agency" compCode="1013" compName="NSA" createdBy="root" url="http://checklists.nist.gov/chklst_detail.cfm?confi"/>
    <PRComp comments="he Center for Internet Security (CIS) is a not-for-profit organization that helps enterprises reduce the risk of business and e-commerce disruptions resulting from inadequate technical security controls, and provides enterprises with resources for measuring information security status and making rational security investment decisions" compCode="1020" compName="CIS" createdBy="root" url="http://www.cisecurity.org/"/>
    <PRComp comments="This is a Cisco document. It outlines the key security elements identified for Network Security Baseline, along with implementation guidelines to assist in their design, integration, and deployment in production networks. " compCode="1022" compName="Cisco Secuirty Baseline" createdBy="root" url="http://www.cisco.com/en/US/docs/solutions/Enterpri"/>
    <PRComp comments="This is the best practices from industry experts to help make audit recommendations in a customers environment. " compCode="1023" compName="360 GRC Best Practice" createdBy="root" url="http://www.360grc.com"/>
    </ParentCompliance>
    <parentriskrecommendationdetails ACTION_FLAG="RulePass" AUDIT_RESULTS="Both_pass_fail_result" CHILD_TYPE="ALL" CMD_CODE="dfg" COMMAND_REF="dfgdf" DEFINITION="dfgdf" DEVICE_RECOM_CATEGORY_CODE="IP - Addressing Services" DEVICE_RISK_CATEGORY_CODE="IP - Addressing Services" DISP_LEVEL="Parent and child result" PARENT_RULE_CODE="PR626" RATING1="3" RATING1_NAME="DISA" RATING2="3" RATING2_NAME="NSA" RATING3="3" RATING3_NAME="Cisco Secuirty Baseline" RATING4="3" RATING4_NAME="CIS" RATING5="3" RATING5_NAME="360 GRC Best Practice" RATING6="3" RATING6_NAME="INTERNAL GROUP POLICY" RATING_IMPACT="Low" RATING_PRIORITY="Low" RATING_URGENCY="Low" RECOMENDATION="dfgdf" WEB_REF="dfgdf" WEIGHTING1="10" WEIGHTING1_NAME="DISA" WEIGHTING2="10" WEIGHTING2_NAME="NSA" WEIGHTING3="10" WEIGHTING3_NAME="Cisco Secuirty Baseline" WEIGHTING4="10" WEIGHTING4_NAME="CIS" WEIGHTING5="10" WEIGHTING5_NAME="360 GRC Best Practice" WEIGHTING6="10" WEIGHTING6_NAME="INTERNAL GROUP POLICY"/>
    </parentruledetails>
    </Parentrule>
    </GRC>

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

  • Problems with character displaying from XML to Java

    Hi to all!
    I am making a flash chat program which basically takes english and chinese
    and talk to java using XML and java server distribute this message to all users,
    While simply using java as a distributor of the data was fine, but when I try to
    keep records of the chat into the mysql database, I realized that all the
    chinese characters are displayed in random characters.
    After some thought, I realized that flash using ASCII number representation
    for each chinese word imay be different from the Java ASCII number representation, therefore, when Java sends
    these ASCII characters to the mysql database, the words is no longer the words I wanted.
    I am using a brute force, which on the flash side, I took the ASCII code of each chinese character that I
    typed and use break and send them to java and recoded in java with java's Chinese character
    and send to the mysql database, well, it works(I tried) but I need to type up at least 3000 characters!!!!!!!!
    this is insane!
    I am also wonder if the problem comes because Java encode Chinese in unicode, so
    it does not recognize the ASCII, and therefore, the result is for sure weird.
    If so, what do I need to do in order to convert ASCII into Unicode????
    sincerely,
    Suansworks

    hello.
    flash have some problems by utf but it seems that your problem is with mysql database because if you want to put utf in mysqk database you need to get latest version that is beta or alpha. please it using with other database that supports utf.

  • Parsing XML using java DOM

    hi
    i am trying to parse a document and change a specific text value within an element althouh when i run the program it changes the nodes text however when i check the xml file it doesnt show the changes it remains the same the code that i am using is as follow iwould be greatful if any one culd help:
    //  ReplaceText.java
    // Reads intro.xml and replaces a text node.
    // Java core packages
    import java.io.*;
    // Java extension packages
    import javax.xml.parsers.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.dom.*;
    // third-party libraries
    import org.xml.sax.*;
    import org.w3c.dom.*;
    public class ReplaceText {
       private Document document;
       public ReplaceText()
          // parse document, find/replace element, output result
          try {
             // obtain default parser
             DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
             // set parser as validating          
             factory.setValidating( true );
             // obtain object that builds Documents
             DocumentBuilder builder = factory.newDocumentBuilder();
             // set error handler for validation errors
             builder.setErrorHandler( new MyErrorHandler() );
      System.err.println( "reading" );
             // obtain document object from XML document
             File f = new File("D:/Documents and Settings/Administrator/Desktop/xml adv java bk/appC/intro.xml");
              System.err.println( "reading" );
             document = builder.parse(f);
    //document = builder.parse( new File( "intro.xml" ) );
    System.err.println( "reading document" );
             // retrieve the root node
             Node root = document.getDocumentElement();
             if ( root.getNodeType() == Node.ELEMENT_NODE ) {
                Element myMessageNode = ( Element ) root;
                NodeList messageNodes =
                   myMessageNode.getElementsByTagName( "message5" );
                if ( messageNodes.getLength() != 0 ) {
                   Node message = messageNodes.item( 0 );
                        System.out.println("iiiii");
                   // create text node
                   Text newText = document.createTextNode(
                      "New Changed Message!!" );
                   // get old text node
                   Text oldText =
                      ( Text ) message.getChildNodes().item( 0 ); 
                   // replace text
                   //message.removeChild(oldText);
                   message.replaceChild( newText, oldText );
             // output Document object
             // create DOMSource for source XML document
             Source xmlSource = new DOMSource( document );
             // create StreamResult for transformation result
             Result result = new StreamResult( System.out );
             // create TransformerFactory
             TransformerFactory transformerFactory =
                TransformerFactory.newInstance();
             // create Transformer for transformation
             Transformer transformer =
                transformerFactory.newTransformer();
             transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
               transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
             // transform and deliver content to client
             transformer.transform( xmlSource, result );
          // handle exception creating DocumentBuilder
          catch ( ParserConfigurationException parserException ) {
             parserException.printStackTrace();
          // handle exception parsing Document
          catch ( SAXException saxException ) {
             saxException.printStackTrace();        
          // handle exception reading/writing data
          catch ( IOException ioException ) {
             ioException.printStackTrace();
             System.exit( 1 );
          // handle exception creating TransformerFactory
          catch (
             TransformerFactoryConfigurationError factoryError ) {
             System.err.println( "Error while creating " +
                "TransformerFactory" );
             factoryError.printStackTrace();
          // handle exception transforming document
          catch ( TransformerException transformerError ) {
             System.err.println( "Error transforming document" );
             transformerError.printStackTrace();
       public static void main( String args[] )
          ReplaceText replace = new ReplaceText();   
    }the xml file that i am using is as follows:
    <?xml version = "1.0"?>
    <!-- Fig. 28.10 : intro.xml             -->
    <!-- Simple introduction to XML markup   -->
    <!DOCTYPE myMessage [
         <!ELEMENT myMessage (message, message5)>
         <!ELEMENT message (#PCDATA)>
         <!ELEMENT message5 (#PCDATA)>
    ]>
    <myMessage>
         <message>welcome to the xml shhhhhushu</message>
         <message5>welcome to the xml shhhhhushu</message5>
    </myMessage>i would be greatful if some one could please help.....

    See if the Text 'oldText' actually has any text within it. Sometimes in DOM parsing, you will get something like:
    Element
       Text (blank)
       Text (actual)
       Text (blank)Whereas you would expect to receive:
    Element
       Text (actual)See if that is the case. If yes, modify your logic to iterate through the child text nodes until one with actual text inside of it (getNodeValue()) is found.
    - Saish

  • Read, Modify and Apply Report XML using Java Script

    Hi Guys,
    Is there any way that we can Pragmatically Read, Modify and Apply Report XML using Java Script or some other way.
    Thanks
    Kaushik
    Edited by: Kaushik K on Jun 20, 2012 8:36 PM

    Requirement ::
    Users should be able to add Column to the Report Dynamically at Runtime.
    (There are around 1000+ Users, Answers Approach is not acceptable)
    So we are planning to provide a Multi Select / Shuttle Box Option for Users to add Columns dynamically. (Only for Table View)
    What we planned to DO ::
    Create a Presentation Variable Prompt, Which reads the Metadata Table (Presentation Table.Column Name, populated using the Metadata Dictionary)
    And Create a report with One Column and the Column Fx like @{var_dynamic_columns}{'"Time"."Year","Time"."Month"'}
    With this, OBIEE is rewriting the Logical SQL Currently as "Select "Time"."Year","Time"."Month" from "A - Sample Sales" "
    But getting an error
    The number of columns returned in retrieving column metadata was invalid (expected: 1; received: 2)
    So we want to see, if we can rewrite the Advanced XML of the Report to have dynamic columns based on the Values from the Presentation Variable.
    Please help me if this is a viable solution or any other better solution.

  • Merge LiveCycle Form with XML using JAVA

    Hello.
    I am trying to find out how to merge non-interactive form with XML (using JAVA) so the users can see the final output form with the data filled in.
    What are my choices..?
    So far, I have created the interactive forms as template using LiveCycle 8 and wrote ASP.NET code to extract data and store it in SQL database when the user fill out and submit the form.
    It works great but another agency wants to access the form as well.
    They told us that they will create the XML themselves from the database, so they just need to combine the form with XML to display it (non-interactive form).
    They want to use JAVA but I am not sure how to do that...
    Any suggestion?

    Assuming that you start with XML in an org.w3c.dom.Document that stores the XML data. Before you can merge it into a form, you have to convert it to a com.adobe.idp.Document object. TO convert a org.w3c.dom.Document to a com.adobe.idp.Document object -- use the following Java code:
    private Document convertDataSource(org.w3c.dom.Document myDOM)
    byte[] mybytes = null;
    try
    //Create a Java Transformer object
    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer transForm = transFact.newTransformer();
    //Create a Java ByteArrayOutputStream object
    ByteArrayOutputStream myOutStream = new ByteArrayOutputStream();
    //Create a Java Source object
    javax.xml.transform.dom.DOMSource myInput = new DOMSource(myDOM);
    //Create a Java Result object
    javax.xml.transform.stream.StreamResult myOutput = new StreamResult(myOutStream);
    //Populate the Java ByteArrayOutputStream object
    transForm.transform(myInput,myOutput);
    // Get the size of the ByteArrayOutputStream buffer
    int myByteSize = myOutStream.size();
    //Allocate myByteSize to the byte array
    mybytes = new byte[myByteSize];
    //Copy the content to the byte array
    mybytes = myOutStream.toByteArray();
    catch (Exception e) {
    System.out.println("The following exception occurred: "+e.getMessage());
    //Create a com.adobe.idp.Document object and copy the
    //contents of the byte array
    Document myDocument = new Document(mybytes);
    return myDocument;
    THen you can merge myDocument into the Form using renderPDFFOrm:
    FormsResult formOut = formsClient.renderPDFForm(
    formName, //formQuery
    myDocument, //inDataDoc
    pdfFormRenderSpec, //PDFFormRenderSpec
    uriValues, //urlSpec
    fileAttachments //attachments
    Hope this helps!

  • XML with Java

    Hi,
    I am new in XML and I need to design a Java GUI interface for managing changes to xml data(inserting, deleting of nodes). But i have no idea on how the communication is going to be established (How to link java to xml..).
    Any help will be very very appreciated!
    Thank You
    cheers,
    jun

    if you use the latest JDK (1.4), you will have all what you need to manipulate XML in Java.
    then follow this tutorial: http://java.sun.com/webservices/docs/1.0/tutorial/doc/JAXPDOM.html
    it'll get you started!

  • Convert MBox into XML into Java Objects

    Hello all,
    this is a general question, i dont know weather there is such libs or not.
    However, please tell me what you know.
    i want to program a java application for searching purpose in Mbox.
    i thought its possible and easier to try to convert the emails from the MBox into XML files, and from these create java objects when i need or even convert the XML into html for viewing.
    Any suggestions are welcome.
    Also antoher solutions are greate.
    thanks in advance!
    Sako.

    I don't know what this MBox you speak of is - I assume it's not the thing I use to hook upa guitar to GarageBand. Maybe you mean it as a generic term for mailbox? The easiest solution (to my mind) would be to use a Java API provided by whatever MBox is. If there is no such thing, then if you get XML-formatted version of the messages I suppose writing code to parse the XML into Java Objects would be a good option if you wanted to do further manipulation of them, but if all you want to do is display them as HTML in a browser then just use XSLT to transform them.
    Good Luck
    Lee

  • How to read  and write XML in java

    I have a code that reads a large XML file, splits it into smaller files, filters and then writes it into a new XML file. My problem is that I had coded the input file name into the code, so that only the specified file can be read. How can I rewrite my code to be able to take any input xml and perform the same operation? Here's a portion of my code below:
                            File file = new File("c:\\APAdjustmentJVDoc_FINAL.xml");
                        output = new BufferedWriter(new FileWriter(file));
                        for (int i = 1; i < 79; i++) {
                             fIStream = new FileInputStream("c:\\APAdjustmentJVDoc_new" + i + ".xml");
                             loRead = new InputStreamReader(fIStream);
                             doc = XMLUtil.transformToNode(loRead, false);
                             System.out.println("Reading from file " + "c:\\APAdjustmentJVDoc_new" + i + ".xml");
                             writeFile(doc, docIdList, output);
                             fIStream.close();
                             loRead.close();
                        System.out.println("Output file complete");
                   } catch (Exception e) {
                        e.printStackTrace();
                   } finally {
                        if (output != null) {
                             output.close();
                        if (fIStream != null) {
                             fIStream.close();
              } catch (Exception e) {
                   e.printStackTrace();
                 

    You need to pass your filename String as a parameter to your functionality. It depends how you're currently set up though. We can't really see the top of your call so it's difficult to determine what you are calling and we don't really know from where you're calling either.
    If you're running standalone, then on launch of the application, you can feed in a file name as an argument that you can read in in String args[] in the main function and pass down to your XML splitter.
    If you're a method in a class that's part of a bigger pile, you can feed the file name as a String to the method from wherever you call from if it makes sense architecturally.
    You might also want to pass down a File object if that makes sense in your current code (i.e. if you're using your file for other purposes prior to the split, to avoid recreating closing/opening for no reason).
    Depends what you're trying to do. If I put together a piece like this, I would probably create an <yourcurrentrootpackage>.xml.splitter package.
    Also, on a side note, you're problem isn't really reading and writing XML in java, but seems more to be making your functionality generic so that any XML file can be split with your code.
    Regards
    JFM

  • Outputting XML in Java

    xmlwriter
    http://www.osjava.org/xmlwriter/
    http://www.osjava.org/xmlwriter/Using.html
    XMLENC
    http://xmlenc.sourceforge.net/
    JDOM
    http://www.jdom.org/
    DOM4J
    http://www.dom4j.org/
    XOM
    http://www.cafeconleche.org/XOM/
    JiBX
    http://www.jibx.org/
    JBind
    http://www.jbind.org/
    XmlBeans
    http://xml.apache.org/xmlbeans/
    JAXB
    http://java.sun.com/xml/jaxb/
    article: Generating XML via Java
    http://builder.com.com/5100-6371-1044810.html

    Also check out the FormattedDataSet at http://www.fdsapi.com

  • Printinting XML in JAVA

    I have the following XML file and the java file to read the xml contents.
    I compiled the java file.When i read it it says,
    parsing error line 0, uri null
    d:\book.xml not found.
    the xml and java file are in same path only. whats the problem?
    following is the code:
    java file
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class ReadAndPrintXMLFile{
    public static void main (String argv []){
    try {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    File fobj=new File("D:\\book.xml");
    System.out.println("file :"+fobj);
    Document doc = docBuilder.parse(fobj);
    // normalize text representation
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
    NodeList listOfPersons = doc.getElementsByTagName("person");
    int totalPersons = listOfPersons.getLength();
    System.out.println("Total no of people : " + totalPersons);
    for(int s=0; s<listOfPersons.getLength() ; s++){
    Node firstPersonNode = listOfPersons.item(s);
    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
    Element firstPersonElement = (Element)firstPersonNode;
    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
    Element firstNameElement = (Element)firstNameList.item(0);
    NodeList textFNList = firstNameElement.getChildNodes();
    System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
    Element lastNameElement = (Element)lastNameList.item(0);
    NodeList textLNList = lastNameElement.getChildNodes();
    System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
    NodeList ageList = firstPersonElement.getElementsByTagName("age");
    Element ageElement = (Element)ageList.item(0);
    NodeList textAgeList = ageElement.getChildNodes();
    System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
    }//end of if clause
    }//end of for loop with s var
    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
    }catch (Throwable t) {
    t.printStackTrace ();
    }//end of main
    FOllowing is the XML file:
    <?xml version="1.0"?>
    <book>
    <person>
    <first>Kiran</first>
    <last>Pai</last>
    <age>22</age>
    </person>
    <person>
    <first>Bill</first>
    <last>Gates</last>
    <age>46</age>
    </person>
    <person>
    <first>Steve</first>
    <last>Jobs</last>
    <age>40</age>
    </person>
    </book>

    I have the following XML file and the java file to
    read the xml contents.
    I compiled the java file.When i read it it says,
    parsing error line 0, uri null
    d:\book.xml not found.
    the xml and java file are in same path only. whats the
    problem?
    following is the code:
    java fileMalisun,
    Is your java pgm. and XML file in the root directory of D: drive? By writing code as File fobj = new File("D:\\book.xml"); you indicate that the file is in the root directory of your D: drive. I just changed the following line:
    File fobj=new File("D:\\book.xml");to
    File fobj=new File("book.xml");and the program worked fine. I hope this helps.

  • Jaxa xml tutorials, does anyone have some tutorial for using xml in java??

    jaxa xml tutorials, does anyone have some tutorial for using xml in java??
    can be dom,sax,jaxp whatever....
    i try to find in google but din't find any complete one....

    dapim wrote:
    jaxa xml tutorials, does anyone have some tutorial for using xml in java??
    can be dom,sax,jaxp whatever....
    i try to find in google but din't find any complete one....I would imagine anyone here would just produce the same set of hits that you did, so why waste our time doing it only to direct you to the same one(s) you already found and rejected.

  • Starting xml with java

    hi all,
    cud any one provide me with the url that contain the examples of how to integrate xml with java.as i am new in this field so i need something from the very basic.and what all stuff do i need on my system to run the code.
    thanx in advance
    anshul

    http://java.sun.com/xml/index.html

  • Building XML from Java

    Hi,
    I would like to know how to include DOC TYPE reference node, when building XML from Java.
    Thanks !!

    SetDocType is available only in JDOM parser. I would like to know is it prossible without that.
    Thanks !!

Maybe you are looking for