Using JAXB to edit XML documents

I am trying to understand how (and whether) JAXB can be used to make the following types of changes to an existing XML document. I know that I can EDIT an XML document using the set methods that are generated by JAXB (in conformance with the XML Schema), and then I create a Marshaller and marshall the root element object.
However, I have not figured out how to do any of the following:
(i) insert a new element
(ii) delete an existing element
(iii) reorder elements.
Here is an excerpt from an XML document:
<directory name="dir">
<file name="file1"/>
<file name="file2"/>
<file name="file3"/>
</directory>
The order in which the file elements appear is significant.
If I want to add a new file (file4), how would I do this? Where would it be added, at the end? What if I wanted to add it after file2?
If I want to delete file1, I don't know how to do that.
Finally, if I want to move file2 after file3, I don't know how to do that.
It seems as though I need access to the underlying com.sun.xml.bind.util.ListImpl (or similar collection object), which holds the actual file elements when JAXB unmarshals the xml file. However, this seems dangerous and I have gotten a concurrent access exception while trying to do something like this. (Another problem has to do with iterators, where I can't iterate through a list and then make a change to the list w/o messing up the iterator.)
If there are any technologies other than JAXB that might accomplish this, but that provide data binding, I would be happy to hear about it. (I could try SAX/DOM/JDOM/DOM4J or XSLT, I guess, but I like the data binding of JAXB.)

As is typical for me, I answered my own questions.
if you are outside of an iterator, you can simply use the:
add(object)
add(position,object)
remove(object)
methods of the List interface to add and remove elements from the list of elements.
Also, if you use a ListIterator, you can call the add() and remove() methods of ListIterator while iterating through the list.
In order to reorder elements in the list, use:
Collections.swap(list,pos1,pos2). Why this method is not built into the List interface itself is beyond me. This was only added in 1.4, btw.

Similar Messages

  • UCCX 8 - Dramatic change in the Create File Document step that is used by the Create XML Document step in order to read an XML file

    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin:0in;
    mso-para-margin-bottom:.0001pt;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-fareast-font-family:"Times New Roman";
    mso-fareast-theme-font:minor-fareast;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;
    mso-bidi-font-family:"Times New Roman";
    mso-bidi-theme-font:minor-bidi;}
    For the last 5 years (and in IPCC3.x/4.x,UCCX/5.x/7.x) I've used the same basic subflow to read a XML document that contains holiday dates where the queue should be closed.  I've re-used this script on 20+ client installs and it's always worked.  The structure of the script allows you to pass the path and filename of the XML document as parameters to the subflow. (The document is in the repository)
    I loaded this script in UCCX 8.0.2 recently and it crashed with a Java.IO error.  It looked like it was trying to read the file system directly and not the repository. (In the Linux appliance model this kind of makes sense but why is the step trying to read the file system directly?)
    So I open a TAC case (SR# 615243125) and TAC tells me that the method of using the Create File Document step is not supported anymore and that I should specify the filename directly in the Create XML Document step
    The problem that I see (aside from having to edit all my scripts that use XML files) is that the Create XML Document step is looking for the input to be a type DOCUMENT and not a type STRING.  This seems to imply that I have to hardcode the document in each script that I deploy for a customer.  When it was a string it was easy to construct the full file path from parameters and pass to the subflow.
    Questions to the group
    #1 Am I missing something here?
    #2  Do you assume that you'll be able to load a script that worked fine in UCCX 7 into UCCX 8 and that it should completely function when you're doing everything according to the step reference documentation.
    #3 Cisco didn’t document this in any way that I can find.
    #4 How can you use the Create XML Document step in a fashion that would let you construct the path of the file and the filename previously in the script so you could pass it to a subflow ?  It would seem this functionality has been killed in UCCX 8
    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin:0in;
    mso-para-margin-bottom:.0001pt;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-fareast-font-family:"Times New Roman";
    mso-fareast-theme-font:minor-fareast;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;
    mso-bidi-font-family:"Times New Roman";
    mso-bidi-theme-font:minor-bidi;}
    (Background)
    Create File Document Step
    The input filename is a STRING, could be an explicit path and filename in the repository or a variable that represents that path and string
    The output of this step is a DOCUMENT to be used in the Create XML Document step
    The string FILE_FullPathHolidayFiles references  en_us\folderName\documentName.xml
    The document was properly uploaded into the repository only, NOT trying to directly read c:\foo\blah…
    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin:0in;
    mso-para-margin-bottom:.0001pt;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-fareast-font-family:"Times New Roman";
    mso-fareast-theme-font:minor-fareast;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;
    mso-bidi-font-family:"Times New Roman";
    mso-bidi-theme-font:minor-bidi;}
    The create XML document input can only be a type DOCUMENT

    #1 Am I missing something here?
    You are mixing two different issues together here.
    The Create File Document step is indeed not needed or supported for creating an XML document. That is why there is a unique step; to trigger XML parsing within the MIVR subsystem.
    Accessing the file system is restricted to a single folder within the VOS model (i.e. 8.0+). This folder is not backed up, replicated, or cleaned up automatically. It was intended to give developers some FS access as a temporary swap location only.
    #2  Do you assume that you'll be able to load a script that
    worked fine in UCCX 7 into UCCX 8 and that it should completely
    function when you're doing everything according to the step reference
    documentation.
    Assume nothing; read the documentation and attend one of the dozens of partner training sessions that CCBU put on advising of the upcoming changes.
    #3 Cisco didn’t document this in any way that I can find.
    You're right, I guess, on the Create File vs. XML Document step. AFAIK Cisco never wrote a notice into the Step Reference Guide explicitly stating that you cannot use the Create File Document although the documentation seemed pretty clear to me without it. File system restrictions are documented in the 8.0 release notes.
    Scripting and Development Series: Volume 2, Editor Step ReferenceUse the Create XML Document step to create a logical document that maps a document to another document variable (where the document has already been pre-parsed as an XML document and is ready to be accessed by the Get XML Document Data step).Use this step before the Get XML Document Data step to obtain data from a document formatted using the Extensible Markup Language (XML).
    #4 How can you use the Create XML Document step in a fashion that would
    let you construct the path of the file and the filename previously in
    the script so you could pass it to a subflow ?  It would seem this functionality has been killed in UCCX 8
    No it hasn't; just concatinate a string to build the Source Document parameter the step needs. Example:  "DOC[" + myFilePath + "]"

  • Help required to edit xml document

    I am new to java and xml compatibility.I just had familiarised SAX parser.
    I now want to familiarse the technology to edit xml document from a java program(more precisely write to an xml file).I came to know about many methods - JAXP DOM method,JAXB api method - and is totally confused.
    Can any body give me guidance about these api's and suggest a method that
    i should follow?
    i repeat that my application will have to frequently edit xml files
    Thank you

    Hi,
    it's very easy to edit and create XML. See examples in docs: http://livedocs.adobe.com/flex/3/langref/XML.html#includeExamplesSummary
    There are many examples how to get attributes and other data.
    You also can set attributes the same way.
    If you have concrete questions, ask.

  • Problem in editing xml document

    Hi,
    Can anybody help me out of this problem basically i want to develop sample prog that will take care of editng the existing xml document eg. i want to edit resource file for the application like if user want to change some property through the user interface and i want to reflect that input to the xml files.
    Help me as soon as possible ............. its very urgent .......................
    Regards
    Sanket

    Output document with a transformer.
    TransformerFactory tFactory =TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
                DOMSource source = new DOMSource(document);
                StreamResult result = new StreamResult(new File("c:/output/output.xml"));
                transformer.transform(source, result);

  • Using parser to parse xml document

    Hi all:
    I have a xml document which has a root element and the a list of elements(same type) underneath it.
    My question is:
    Is there a restriction on the number of elements(same type) that you can extract from the Document?
    Thanks.
    Rino

    If you use DOM of JDOM, you will have a problem when you run out of system memory.
    If you use SAX, the parser will throw events with the required data for the current node (element, data, attribute). Once the event has been processed, the data is out of scope (unless you still hold a reference to it).
    If you use SAX, you are able to process each node without keeping the data from that node any longer than you like. Unless you have to have the entire document available, I would suggest using SAX.

  • How to use OAF transform sotred xml documents using XSLT...

    Does anyone have any experience using XSLT in OAF? Specifically, I have xml documents stored in a clob to which I wish to apply an XSLT transformation and then store the transformed documents back into the clob. Is there a way to apply an XSLT transformation using say BI-Publisher via OAF?

    "XML DIFF" are the keywords you can use to search for products that do this. Last time I looked there was a lot of XML Diff implementations, but none of them produced human-readable output that I really liked. I expect that's because XML diff is an easy thing for people to ask for but not an easy thing to do, given the considerable number of ways there are to change a document.

  • Use JAXP for creating XML document

    Hi,
    I have used JAXP to create a XML docuemnt. But when I use Jaxp to parse it, it returns parsing error ''null''.
    I open the XML document in XMLspy and save again, then it can be parsed.
    Any suggestion for that? Thanks a lot.

    Are there any differences between the version created with jaxp and the one with xmlspy? are you using the validating parser? if you aren't you might be having trouble with white space. just a guess.

  • Best class to use to cache an XML document

    Hello all,
    I have an utility class representing an XML document, used withing a web application. This document shall be cached in the session since within a request and during the sessions I read it often and to several other things like XPath and XSLT.
    But I am having problems due to this Bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6322678
    and keep bad file descriptor errors due to these stream "specialities". There is a standard way of using cached+precompiled XSL templates and I wonder if there is a similar things for XML documents.
    So I need an internal variable in my class containing the raw XML document - so using streams is not an ideal solution in regards of the bug - i am getting "bad file descriptor" errors from time to time.
    I am playing with the idea of storing the XML document within a simple String and create the required Class from it for the according operations like XPath evaluation and XSL transformation. But I think that is quite more resource hungry than reading the XML document from the filesystem each time...
    Has anyone some hints on how to keep an XML document in memory internally?
    Thanks and regards,
    Timo

    Rehi,
    So, everything works really fine! Thanks. As promised, here some examples
    with bad indentations etc...:
    Doing XSL transformation:
    import java.io.StringWriter;
    import org.w3c.dom.Document;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.Templates;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.stream.StreamResult;
    TransformerFactory tFac = TransformerFactory.newInstance();
    Templates compiledXslt = tFac.newTemplates(sheet);
    Transformer transformer = compiledXslt.newTransformer();
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(new DOMSource(this.doc), sr);
    System.err.println(sw.toString());************************
    Doing XPath was a surprise and was originally my problem (I called evaluate() with an InputStream that occassioannly failed), I tried also here with new DOMSource() what also failed although not being null or so... funny: evaluate() can directly be called w/ dom.Document:
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    (this.doc is a org.w3c.dom.Document)
    public String getXPathEvaluationAsString(String expr) {
         try {
              XPath xp = XPathFactory.newInstance().newXPath();
              return (String)xp.evaluate(
                   expr,
                   this.doc,
                   XPathConstants.STRING
         } catch(Exception e) {
              e.printStackTrace();
         return " ";
    }Thanks and regards,
    Timo

  • Editing XML documents from iFS WebUI

    When I click on an XML document within the iFS WebUI, it opens the file and shows it to me within Internet Explorer.
    I want the document to be opened on my workstation with Arbortext Epic Editor, but IE keeps trying to display it.
    Has anyone had a problem like this? I don't want Internet Explorer to open the document, but what the XML file is associated with within Windows...
    I have tried changing the MIME type for XML documents within JWS from default to application/octet-stream in an attempt to force IE to pass it to the operating system... but it didn't work.. unless I change the wrong mime.properties file...
    Anyone have a solution?

    Did you change your settings in IE for that mimetype ?
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by David Thomas ([email protected]):
    When I click on an XML document within the iFS WebUI, it opens the file and shows it to me within Internet Explorer.
    I want the document to be opened on my workstation with Arbortext Epic Editor, but IE keeps trying to display it.
    Has anyone had a problem like this? I don't want Internet Explorer to open the document, but what the XML file is associated with within Windows...
    I have tried changing the MIME type for XML documents within JWS from default to application/octet-stream in an attempt to force IE to pass it to the operating system... but it didn't work.. unless I change the wrong mime.properties file...
    Anyone have a solution?<HR></BLOCKQUOTE>
    null

  • Use JDBC to Access XML Documents in Oracle XML DB

    Hi folks,
    From the Oracle XML DB Developer's Guide 10g Release 1 (10.1) Chapter 12 Java API for XMLType, it show several examples for how java application use JDBC to access xml in XMLDB:
    1. use getOPAQUE() on XMLTYPE table/column and then call XMLTYPE.createXML();
    2. use getCLOBVal()/getStringVal()/getBLOBVal() in SQL statement;
    3.use getObject on the result and cast directly to XMLType;
    Among these 3 options, which is supposed to be the fastest way? Any difference between thin and oci?
    I have run some tests about that and the result is the second option (with thin driver) is the fastest. It surprises me because I think oci should be faster than thin. Does the result make sense?
    Thanks.

    Have you tried to trace your sessions to see how much work is happening? Traces should give you quantifiable information on exact times and access paths to the data.
    Below is a link to an O'Reilly book excerpt on Java programming with JDBC. Slightly data, but may be of assistance.
    http://www.onjava.com/lpt/a//onjava/excerpt/oraclejdbc_19/index.html

  • Editing xml documents

    My application uses xml for data persistency. My question is:
    1. is there a way to partially edit part of the xml file? because if I make some small changes to my data, i wish to save just that part.
    2. Or I can just save the whole thing and overwrite the orignal file entirely, is this a common practice?
    thanks!

    A javax.xml.transform.Transformer  transform method stores a Documentnode or a DocumentFragment node.
    Transformer transformer;
    Document document;
    Node node;
    DocumentFragment documentFragment=document.createDocumentFragment();
    documentFragment.appendChild(node);
    transformer.transform(new DOMSource(document), new StreamResult(new File("c:/output/output.xml")));
    transformer.transform(new DOMSource(documentFragment), new StreamResult(new File("c:/output/outputNode.xml")));

  • How to use NodeIterator on an XML document

    I have been trying to create a NodeIterator using the following code:
    try
    FileInputStream inStream;
    Document doc;
    String xmlDocumentPath = "I have a real path here";
    inStream = new FileInputStream(xmlDocumentPath);
    DOMParser parser = new DOMParser();
    parser.parse(inStream);
    doc = parser.getDocument();
    Node root = doc.getDocumentElement();
    formInputFilter filter = new formInputFilter();
    DocumentTraversal traverse = (DocumentTraversal)doc;
    NodeIterator iter = traverse.createNodeIterator(root, NodeFilter.SHOW_ALL, filter, true);
    Node n = (Node)iter.nextNode();
    while (n != null)
    System.out.println(n.getNodeName());
    catch (Exception e)
    System.out.println(e.toString());
    When the nextNode method is executed I get an NPE. Looking in the iterator it shows the value of next as null when it is created. I have found a couple of code sources that all show this as the correct way to create a NodeIterator and I can't figure out what I am doing wrong. I have tried creating it with and without my filter and I still have the same problem. I had other code that could loop through the XML file that worked but the NodeIterator would be much simpler to use. Anyone have a suggestion.

    Using JDev 9.0.3.1, and with a C:\temp\test.xml file setup ahead of time, running the following program works for me just fine. How is yours different?
    package test;
    import java.io.FileInputStream;
    import oracle.xml.parser.v2.DOMParser;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.traversal.DocumentTraversal;
    import org.w3c.dom.traversal.NodeFilter;
    import org.w3c.dom.traversal.NodeIterator;
    public class Test {
      public static void main(String[] args) throws Throwable {
        Test t = new Test();
        t.test();
      void test() throws Throwable {
        String xmlDocumentPath = "c:\\temp\\test.xml";
        FileInputStream inStream = new FileInputStream(xmlDocumentPath);
        DOMParser parser = new DOMParser();
        parser.parse(inStream);
        Document doc = parser.getDocument();
        Node root = doc.getDocumentElement();
        MyNodeFilter filter = new MyNodeFilter();
        DocumentTraversal traverse = (DocumentTraversal)doc;
        NodeIterator iter = traverse.createNodeIterator(root, NodeFilter.SHOW_ALL, filter, true);
        Node n = null;
        while ((n = (Node)iter.nextNode()) != null) {
          System.out.println(n.getNodeName());
      class MyNodeFilter implements NodeFilter {
        public short acceptNode(Node n){
          return FILTER_ACCEPT;
    }

  • Error while generating an XML Document from XML Schema with JAXB

    Hi,
    I am following this OTN tutorial to generate the XML document from Java classes got from the XSD document.
    http://www.oracle.com/technology/pub/notes/technote_jaxb.html
    I am able to generate all the Java classes but getting error on compiling the XMLConstructor.java class which is use for generating the XML document :
    I am using JDK 1.5 and
    Oracle 10g XML Developer's Kit (XDK) Production for Java. xdk_nt_10_1_0_2_0_production
    (though these are warnings I am not able to run it.)
    Error
    C:\Prototype\classes\jaxbderived\catalog>javac -Xlint XMLConstructor.java
    warning: [path] bad path element "%CLASSPATH%": no such file or directory
    XMLConstructor.java:42: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
    journalList.add(journal);
    ^
    XMLConstructor.java:46: warning: [unchecked] unchecked call to add(E) as a membe
    r of the raw type java.util.List
    articleList.add(article);
    Thanks
    Sanjeev ([email protected])

    Use JDK 1.4.

  • Problem unmarshalling xml using JAXB

    I am using JAXB for processing xml, which comes from an external source. Most often, the xml gets changed from external source which causes the error during unmarshalling as the xsd has not changed. Is there a way to process the xml in same way even if xsd hasn't changed, like converting new xml to one as per xsd etc. Someone has mentioned using xslt, but I would like to get more ideas on any other technologies or third party tools to overcome this issue so that I do not have to reply upon changing xsd everytime. Thanks

    Most often, the xml gets changed from external source which causes the error during unmarshalling as the xsd has not changed.So, you've got garbage input. Your goal should be to stop that from happening rather than trying to make it work.
    so that I do not have to reply upon changing xsd everytimeIf you have to keep changing the schema then perhaps JAXB wasn't a suitable technology choice here. Or maybe the design wasn't done properly. Or maybe (see earlier comment) the input files aren't being produced properly. At any rate you need to fix the underlying problem before writing code.

  • Error when reading data from XML using JAXB?

    Hi all,
    I get the error message when reading data from XML using JAXB.
    [org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.]
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException
    (AbstractUnmarshallerImpl.java:315)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:481)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:168)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    I don't find the reason, please help!
    Thanks in advance!

    The problem is sovled.

Maybe you are looking for