Creating a node in an XML Document

Hi!
i need to insert a new element in an existing xml document. for example,
<bookinfo>
<book>
<bookname>A</bookname>
<author>B</author>
</book>
<book>
<bookname>C</bookname>
<author>D</author>
</book>
</bookinfo>
In this document if i want to insert another element using Xpath, say,<publisher> in <book> node, how to insert it.
I'm using DOM parser for parsing the xml file.
Any help to solve this issue appreciated.
Thanks in advance.

final class Foo {
    private static final String MARKUP =
        "<bookinfo>\n" +
          "<book isbn='1234'>\n" +
          "<bookname>A</bookname>\n" +
          "<author>B</author>\n" +
          "</book>\n" +
          "<book isbn='5678'>\n" +
          "<bookname>C</bookname>\n" +
          "<author>D</author>\n" +
          "</book>\n" +
          "</bookinfo>";
    private Foo() {
        super();
    public static final void main(final String[] args)
        throws XPathExpressionException {
        String isbn = args.length > 0 ? args[0] : "1234";
        String publisher = args.length > 1 ? args[1] : "Sample Publisher";
        Document document = ...  // Initialize somehow
        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = "//bookinfo/book[@isbn=" + isbn + "]";
        Element book = (Element) xpath.evaluate(expression, document.getDocumentElement(), XPathConstants.NODE);
        if (book == null) {
            throw new RuntimeException("Unable to find ISBN " + isbn);
        Element newPublisher = document.createElement("publisher");
        newPublisher.setAttribute("name", publisher);
        book.appendChild(newPublisher);
}- Saish

Similar Messages

  • How to delete a node in an XML document

    Hi,
    My flex plugin loads an XML document that is passed in from
    the ExternalInterace. I have a List control that displays data from
    this XML document.
    The XML looks like:
    <document>
    <response>
    <objectlist>
    <list type="typeValue">
    <object type="typeValue" name="Name Value" id="GUID
    Value1">
    <params>
    <params>
    </object>
    <!-- more objects in this list -->
    </list>
    </objectlist>
    </response>
    </document>
    I set the list dataProvider to
    xmlDoc.response.objectlist.list.object
    Thing is, I want to remove one of the object nodes before I
    display the data (that is, i dont want one of the nodes in the XML
    document to appear in the list).
    How do I do this? I could not find any way to delete an
    existing node in the XML api.
    -Gaurav

    You can either use the "delete" operator:
    delete xmlDoc.response.objectlist.list.object[5]
    where the object to be deleted might be the fifth down
    (you'll have to play with your xml in debug to get the actual
    values down) or convert to xmlListCollection. The xmlListCollection
    provides easy methods to remove the offending nodes or you may
    provide a filterFunction for the collection which will "hide" the
    node.

  • Creating an Element for an XML Document

    Assuming I have an XML file
    file.xml
    <root>
    <child1>
    <child2>
    <child100>
    <root>
    i do
    SAXBuilder parser = new SAXBuilder();
    doc = parser.build(file);
    root = doc.getRootElement();This returns a root elemnet for the entire tree.Now my question is how do i create a root element for say jus the top 10 children? That is, is there a way i can create a document just reading the first 10 elements from the file tree above so that when i do a getChildren on root I should have only 10 elements in the list.

    | 1. How are the attributes of an XML element can be stored to the database
    XML SQL Utility (which XSQL uses under the covers) only stores
    documents in the canonical format. You'll need to use an XSLT
    transformation to transform data into the canonical format
    (including transforming attribute values into elements whose
    names correspond to the column in which you'd like to store it)
    | 2. How can I store a single XML document to multiple database tables?
    I outline several techniques for this in my upcoming
    O'Reilly book, "Building Oracle XML Applications".
    The basic idea is to either:
    (1) Use an Object View with an INSTEAD OF INSERT trigger, or
    (2) Use a technique that transform the inbound document
    into a multi-table insert-format and passes each
    relevant part for insert to the XML SQL Utility separately.
    null

  • How do I add (or insert) a node into an XML document with JSTL?

    Dear all,
    I am trying to use JSTL to store some data from a form into XML. However, I have read many articles in JSTL and only found that it can only be, as far as those articles are concerned, used to "read" data from XML files, but not "write" to them.
    Am I missing something in JSTL? Or, if I want to write to an XML file (e.g., insert a new node, or modify a node's data), will I have to write my own bean and then use <c:usebean />?
    Thanks very much in advance.
    Regards,
    Robert

    JSTL is not a programming language in and of itself. It is intended to help you to write scriptlet free JSPs.
    JSP pages (by one school of thought) are intended to function as the "View" in a Model-View-Controller architecture.
    Being a view, JSP pages should be able to look at things - but not touch.
    The standard pattern is to go to a servlet first, which invokes the logic, and then forwards to a JSP for rendering.
    Editing XML by adding new nodes etc etc is thus a function of the java code layer - servlet/action whatever you want to call it.
    Giving you the power to edit XML documents via JSTL (ie on a JSP page) takes away from purity of the MVC design.
    Hence why they don't provide the tags for manipulating XML, and only provide the database tags with a disclaimer that they should only be used for prototypes/trivial apps!
    JSTL is designed to replace scriptlet code on a JSP page.
    It can replace 99% of scriptlet code. The other 1% shouldn't be on the JSP in the first place :-)
    cheers,
    evnafets

  • Traversing the entire nodes of an xml document ?

    Hi,
    I want to traverse through the entire nodes of an if_ixml_document. which is the best way to do this?
    Please find the sample document.
    <text>
        <id>
             <guid auto="false">
                   432543254543
             </guid>
        </id>
         <title>
             <short_title italics="on">
                    <bold language = "german">
                         "Hello"
                   </bold>
            </short_title>
         </title>
    </text>
    In this document, i need to traverse through the nodes <text>, <id>, <guid> , <title>, <short_title>, <bold> etc.
    Thanks in advance
    Regards,
    Ishara

    Hi,
    there are lots of examples in SDN. Could you try, and revert back in case of specific issue?
    There are also examples in SAP library: [SAP Library: Parsing an XML document DOM-based|http://help.sap.com/saphelp_nw70/helpdata/en/86/8280d212d511d5991b00508b6b8b11/frameset.htm ], [SAP Library: Traversing the DOM tree|http://help.sap.com/saphelp_nw70/helpdata/en/86/8280de12d511d5991b00508b6b8b11/frameset.htm ], [SAP Library: Traversing the DOM tree with iterators|http://help.sap.com/saphelp_nw70/helpdata/en/86/8280e112d511d5991b00508b6b8b11/frameset.htm ], ...
    And there is demo program: BCCIIXMLT12
    Sandra

  • How can I use DOM to copy Nodes between different XML Document ?

    Can I copy one Node or Element from one XML Document to another Document by DOM ?
    Because I use the Xerces , but it is not work if I want to copy Node between different Document, or I am doing something wrong. Anyone can help me , I will deeply appreciated !!

    check out the importNode() method of Document.

  • How to append nodes to the xml document

    hi
    when i run the servlet program i want to append nodes to existing to nodes;but actually it is overwriting the nodes;what changes should i made to get desired output
    package example;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.*;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.StringWriter;
    import java.io.IOException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Text;
    public class XMLController extends HttpServlet
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    String fname="name.xml";
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder db = fac.newDocumentBuilder();
    Document doc = db.newDocument();
    Element rt = doc.createElement("India");
                   Element main1 = doc.createElement("IndianPlayer");
                   Element productnames1 = doc.createElement("Name");
                   Text product1 = doc.createTextNode(request.getParameter("name1"));
                   Element price1 = doc.createElement("Age");
                   Text priceValues1 = doc.createTextNode(request.getParameter("age1"));
                   productnames1.appendChild(product1);
                   price1.appendChild(priceValues1);
                   main1.appendChild(productnames1);
                   main1.appendChild(price1);
                   rt.appendChild(main1);
         doc.appendChild(rt);
    saveDocAsFile(doc,fname);
    catch (ParserConfigurationException e) {
    e.printStackTrace();
    public static void saveDocAsFile(Document doc, String fname) {
    try {
    TransformerFactory tfFac = TransformerFactory.newInstance();
    // use null trandformation
    Transformer tf = tfFac.newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT,"yes");
    tf.transform(new DOMSource(doc), new StreamResult(fname));
    /* catch (IOException ioe) {
    ioe.printStackTrace();
    catch (TransformerException e) {
    e.printStackTrace();
    bye
    chaitanya

    Adding a Node to a DOM Document
    http://javaalmanac.com/egs/org.w3c.dom/AddNode.html

  • Need help in creating header node at reciver XML file?

    Hello All,
    Iam creating proxy to file scenario.....at receiver side iam creating XML file like below.
    <?xml version="1.0" encoding="UTF-8" ?>
    <OrderTransaction>
    <TransactionInformation Version="2.0.0">
      <DocId>0180000186</DocId>
       <Sender>........
      </OrderTransaction>
    bit now client require one header node like below
    <!DOCTYPE OrderTransaction PUBLIC "Order" "Order.dtd">
    now th recevier xml need to look like
    <?xml version="1.0" encoding="UTF-8" ?>
    <OrderTransaction>
    <!DOCTYPE OrderTransaction PUBLIC "Order" "Order.dtd">
    <TransactionInformation Version="2.0.0">
      <DocId>0180000186</DocId>
       <Sender>........
      </OrderTransaction>
    how to add that node........... i cant add it as node element............ Please help me out.
    Thanks and Regards,
    Chinna
    Edited by: chinnasapxi on Mar 16, 2010 8:11 PM

    Hi Chinna,
    Probably writing a script and calling in receiver file adapter after message processing and in the script just add the line in the 3rd line and then put the rest.
    Regards,
    ---Satish

  • How to add a new node into existing XML Document

    I have a very simple question. I use XML as input argument for PL/SQL procedure that inserts data into the corresponding table. All I have to do is to add a new tag for Primary Key column and put sequence.NEXTVAL - value into it.
    <ROWSET>
    <ROW>
    -- Add <ID_table_name> value </ID_table_name> ??????
    <FIELD1>data1</FIELD1>
    <FIELD2>data1</FIELD2>
    </ROW>
    </ROWSET>
    I've parsed XML, but I couldn't find the way how to insert the new NODE.
    If you know how to use packages XMLDOM, XMLParser for this purpose, please help me!
    Oracle version 8.1.7

    DOMParser parser=new DOMParser();
    XMLDocument xmlDocument=parser.getdocument();
    Node node=xmlDocument.selectSingleNode("/ROWSET/ROW");
    Element element=xmlDocument.createElement(String tagName)
    node.appendChild(element);

  • How to extract the nodes of any given XML document ???

    Hello,
    Greetings! It is an interesting forum.
    A Snippet of XML Schema PurchaseOrder.xsd as given in user guide is as follows
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xdb="http://xmlns.oracle.com/xdb"
    version="1.0" xdb:storeVarrayAsTable="true">
    <xs:element name="PurchaseOrder" type="PurchaseOrderType"
    xdb:defaultTable="PURCHASEORDER"/>
    <xs:complexType name="PurchaseOrderType" xdb:SQLType="PURCHASEORDER_T">
    <xs:sequence>
    <xs:element name="Reference" type="ReferenceType" minOccurs="1"
    xdb:SQLName="REFERENCE"/>
    <xs:element name="Actions" type="ActionsType" xdb:SQLName="ACTIONS"/>
    <xs:element name="Reject" type="RejectionType" minOccurs="0"
    xdb:SQLName="REJECTION"/>
    <xs:element name="Requestor" type="RequestorType"
    xdb:SQLName="REQUESTOR"/>
    <xs:element name="User" type="UserType" minOccurs="1"
    xdb:SQLName="USERID"/>
    <xs:element name="CostCenter" type="CostCenterType"
    xdb:SQLName="COST_CENTER"/>
    <xs:element name="ShippingInstructions" type="ShippingInstructionsType"
    xdb:SQLName="SHIPPING_INSTRUCTIONS"/>
    <xs:element name="SpecialInstructions" type="SpecialInstructionsType"
    xdb:SQLName="SPECIAL_INSTRUCTIONS"/>
    <xs:element name="LineItems" type="LineItemsType"
    xdb:SQLName="LINEITEMS"/>
    </xs:sequence>
    </xs:complexType>
    full schema is available in url
    http://download-west.oracle.com/docs/cd/B12037_01/appdev.101/b10790/xdb03usg.htm#BABBGIED
    The views use XPath expressions and functions such as extractValue() to define the mapping between columns in the view and nodes in the XML document. The following view is created on purchase order schema.
    Creating Relational Views On XML Content
    CREATE OR REPLACE view PURCHASEORDER_MASTER_VIEW
    (REFERENCE, REQUESTOR, USERID, COSTCENTER,
    SHIP_TO_NAME,SHIP_TO_ADDRESS, SHIP_TO_PHONE,
    INSTRUCTIONS)
    AS
    SELECT extractValue(value(p),'/PurchaseOrder/Reference'),
    extractValue(value(p),'/PurchaseOrder/Requestor'),
    extractValue(value(p),'/PurchaseOrder/User'),
    extractValue(value(p),'/PurchaseOrder/CostCenter'),
    extractValue(value(p),'/PurchaseOrder/ShippingInstructions/name'),
    extractValue(value(p),'/PurchaseOrder/ShippingInstructions/address'),
    extractValue(value(p),'/PurchaseOrder/ShippingInstructions/telephone'),
    extractValue(value(p),'/PurchaseOrder/SpecialInstructions')
    FROM PURCHASEORDER p;
    When we register XML Schema in Oracle 9i, the schema elements of XML documents are stored as XMLType, that is, stored using object-relational storage techniques.
    For a small schema, we could build the above view manually, but for large/nested schema, if we have query to build XML documents node list, it will help us to build Relational Views on XML Content.
    How do we extract the nodes of any given XML document through O-R structures or XML DB using XML DB functions?
    Any alternate thoughts are welcome.
    I appreciate your help.
    Regards
    Ram

    Ram
    Once again, I do not think that you can solve the problem you are trying to solve. Fundamentally you need to determine for a given element of a given complex type what are it's child elements. For each of those elements you then need to find out whether or not it in turn has child elements...
    Then you have to think about elements defined as ref rather than type, elements that are substituteable, and the rest of possibilities that can be described with XML Schema.
    If you can solve that problem you're a better man than I as the saying goes. Anyone rather than give you a fish, I'll show you how to at least put a worm on the hook..
    The following query gets the names of the elements inside a each of the global complex types
    Good luck, if you come up with a query to do this I'd love to see it...
    SQL> column COMPLEX_TYPE format A32
    SQL> column ELEMENT format A32
    SQL> --
    SQL> select extractvalue
    2 (
    3 value(ct),
    4 '/xs:complexType/@name',
    5 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
    6 ) COMPLEX_TYPE,
    7 extractvalue
    8 (
    9 value(et),
    10 '/xs:element/@name',
    11 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
    12 ) ELEMENT
    13 from resource_view,
    14 table
    15 (
    16 xmlsequence
    17 (
    18 extract
    19 (
    20 res,
    21 '/r:Resource/r:Contents/xs:schema/xs:complexType',
    22 'xmlns:r="http://xmlns.oracle.com/xdb/XDBResource.xsd"
    23 xmlns:xs="http://www.w3.org/2001/XMLSchema"')
    24 )
    25 ) ct,
    26 table
    27 (
    28 xmlsequence
    29 (
    30 extract
    31 (
    32 value(ct),
    33 '/xs:complexType/*/xs:element',
    34 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
    35 )
    36 )
    37 ) et
    38 where equals_path(res,'/home/SCOTT/poSource/xsd/purchaseOrder.xsd') = 1
    39 /
    COMPLEX_TYPE ELEMENT
    -------------------------------- ------------------------PurchaseOrderType Reference
    PurchaseOrderType Actions
    PurchaseOrderType Reject
    PurchaseOrderType Requestor
    PurchaseOrderType User
    PurchaseOrderType CostCenter
    PurchaseOrderType ShippingInstructions
    PurchaseOrderType SpecialInstructions
    PurchaseOrderType LineItems
    LineItemsType LineItem
    LineItemType Description
    LineItemType Part
    ActionsType Action
    RejectionType User
    RejectionType Date
    RejectionType Comments
    ShippingInstructionsType name
    ShippingInstructionsType address
    ShippingInstructionsType telephone
    19 rows selected.

  • How to automatically create xml documents ?

    Hi,
    I have created an xml form with specific fields and properties. Now, I want to automatically create a large amount of xml documents based on it.
    Is there any means to do this ?
    Thanks,
    Loïc LEVEUGLE

    You cannot automate applying usage rights with Acrobat. For that you'd need to use Adobe's LiveCycle Reader Extensions.
    How exactly are you currently converting XML into fillable forms? Are you using an XDP to somehow convert to an XFA-based PDF?

  • Create DTD from XML document

    Hello,
    I have a little problem creating a DTD from an XML document. The XML document looks the following:
    <data name="data1">
    <value id="abc" name="value1" />
    <value id="def" name="value2" />
    <value id="ghi" name="value3" />
    </data>
    <data name="data2">
    <value id="123" name="valueA" />
    <value id="456" name="valueB" />
    <value id="789" name="valueC" />
    </data>
    The problem concerns the attribute list of the value element,
    on the one hand I could create a DTD like this:
    <!ATTLIST value id CDATA #REQUIRED
    name CDATA #REQUIRED
    >
    On the other hand I could do it like this:
    <!ATTLIST value id (abc|def|ghi|123|456|789) #REQUIRED
    name (value1|value2|value3|valueA|valueB|valueC)
    #REQUIRED
    >
    Now I don't know what's the right way. I would be glad if anybody could give me support for my problem.
    Thank you very much,
    Findus

    No...this is not the solution for my problem. The first problem with the code you posted is that I can create a valid XML document like this:
    <data name="data2">
    <value id="123" name="value1" />
    <value id="456" name="value2" />
    <value id="789" name="value3" />
    </data>
    (Please compare to the lines below in order to recognize the difference)
    I want the user to create only documents like this:
    <data name="data2">
    <value id="123" name="valueA" />
    <value id="456" name="valueB" />
    <value id="789" name="valueC" />
    </data>
    So I want to define special attribute pairs in my DTD, like ' the value attribute id="123" works only with the attribute name="valueA"! '
    Is it possible to do so ?
    Thanx a lot,
    Findus

  • Manipulating an XML document!

    Hi every1,
    I am working on my dissertation which is based on XML. I need 2 b able 2 change the text of a node in an XML document.
    E.g., <price> </price>.
    I need 2 insert a value betweem these tags.
    I have downloaded JAXP, but it seems 2 b mising a package named xmlDocument.
    Can any1 help?
    Thanx!

    I am using Xerces for creating XML documents.
    If you have created an element, you can use the method createTextNode on your document object in order to create the text. Once you have done this, you can call the appendChild method on the element to add the text. E.g.
    Element element = xmlDoc.createElement("price");
    Text elementText = xmlDoc.createTextNode("1.99");
    element.appendChild(elementText);
    This would produce the following:
    <price>1.99</price>
    This is the Xerces implementation but there should be similar functionality within most of the XML api's.
    Hope this helps.

  • How to set the root path of XML document when calling Inserting procedure

    Hi,
    I was create a procedure to insert XML Document in to DBMS Tables, but i am not able to set the Start root element in calling procedure.
    My calling procedure is
    exec insXmldoc('pmc_sample.xml', 'pmc')
    When i am calling this procedure i got this error
    11:23:54 Error: ORA-29532: Java call terminated by uncaught Java exception: oracle.xml.sql.OracleXMLSQLException: Start of root element expected.
    ORA-06512: at "SYS.DBMS_XMLSAVE", line 65
    ORA-06512: at "SCOTT.INSPROC", line 8
    ORA-06512: at line 2
    I am checking my XML file using XML Validator. My XML file was parsed with out errors.
    Please give the solution,and tell me where i did wrong in my calling procedure.
    suppose i have this XML file in local E drive ,how to set the path for that XML file in my calling procedure.

    Hi, I am doing the code likthis,please give the solution.
    SQL> create or replace procedure insProc(xmlDoc IN CLOB, tableName IN VARCHAR2) is
    2 insCtx DBMS_XMLSave.ctxType;
    3 l_ctx dbms_xmlsave.ctxtype;
    4 rows number;
    5 begin
    6 insCtx := DBMS_XMLSave.newContext(tableName); -- get the context handle
    7 rows := DBMS_XMLSave.insertXML(insCtx,xmlDoc); -- this inserts the document
    8 DBMS_XMLSave.closeContext(insCtx); -- this closes the handle
    9 end;
    10 /
    Procedure created.
    SQL> begin
    2 insProc('/usr/tmp/ROWSET.xml', 'emp');
    3 end;
    4 /
    begin
    ERROR at line 1:
    ORA-29532: Java call terminated by uncaught Java exception: oracle.xml.sql.OracleXMLSQLException:
    Start of root element expected.
    ORA-06512: at "SYS.DBMS_XMLSAVE", line 65
    ORA-06512: at "SCOTT.INSPROC", line 7
    ORA-06512: at line 2
    Kishore B

  • XML document creation

    Does anyone know of a Javascript or PHP script that will
    allow a client to create new and update existing xml documents that
    can be used with the Spry Dataset, through an admin area?

    I don't know of such a system. We do have a script that can
    convert queries to XML:
    http://labs.adobe.com/technologies/spry/samples/utils/query2xml.html
    And I know there are PHP scripts for inserting and updating
    records in a database, which might be easier.
    Hope this helps,
    Donald Booth
    Adobe Spry Team

Maybe you are looking for

  • Flickering Issue with RGB Curves in Adobe Premiere CC (2014) version

    I've been an Adobe Premiere user since Premiere 6.5 and have never encountered any serious issues with the software. However in this most recent Creative Cloud update I am have a flickering issue when using RGB Curves, the color correction effect I u

  • MSS reports displaying Employee Information iView

    Hi all, I'm currently working on MSS project where I'm trying to show reports on MSS portal. I have done the neccessary configurations regarding tables: T77MWBS (Manager's Desktop Senarios) T77MWBFCD (Function Code Definitions) T77MWBFCO (Object-depe

  • Enable shadow copy on failover disk

    Hello!  I have: 1) Failover cluster with 2 hosts on Windows server 2012 r2 2) Role: File Server How i can create\enable shadows copy for cluster disk (File server disk) to another disk? C уважением к Вам, Я

  • MDM JAVA API beginners queries

    Hi, I am a beginner for Web Dynpro. I am working on MDM and i need to use the MDM JAVA API I have downloaded the zip files and reading the documentation. I need guidance on how to proceed. Kindly help thank you bhakti

  • How to use image and text in same component

    Hello Do you know how to use image and text in same component in java ? because i need this in my project ,which is chat application , to put the received text and any image if it is need within the text