GetChildNodes() and getElementsByTagName()

hi,
i'm using java's built-in DOM xml parser. i have a very simple xml document:
<?xml version="1.0" encoding="iso-8859-2"?>
<form title="BSA" x="150" y="150" w="240" h="180">
     <label name="label1" text="abcd: "
          x="10" y="10" w="100" h="20" />
     <border>
          <label name="label2" text="123"
               x="120" y="10" w="100" h="20" />
     </border>
</form>
my problem is the following:
i only need the elements that are direct children of the <form> element (or direct children of any other element).
however, if i call the getElementsByTagName("label") method on the <form> element, i get ALL the elements named "label" in the document.
in this case, getElementsByTagName() returns:
<label>
<label>
if i call the getChildNodes() method on the same element, i get twice as many elements as there are direct children in the <form> element.
like this:
getChildNodes() output:
#text
<label>
#text
<border>
i don't know where the "#text" elements come from and what they represent, but there's allways one for each child element.
so, how do you get all direct children of an element?
i coluld just discard the "#text" elements but i'd sitll like to know what they are and whether there could be some other "invisble" "#something" elements.
thanks

The # text nodes are ignorableWhitespace nodes.
Refer to http://java.sun.com/xml/jaxp/dist/1.1/docs/tutorial/dom/2b_display.html

Similar Messages

  • NodeList and getElementsByTagName

    Hi guys, I have a great problem, and I cannot solve them, therefor I like get some your help!!!!
    I have a xml document:
    <transformers>
        <transformer>
            <name>transformer1</names>
        </transformer>
            <transformer>
            <name>transformer2</names>
        </transformer>
            <transformer>
            <name>transformerN</names>
        </transformer>
    </transformers>And I wanna create a function that remove a "transformer" based on the name value. Then I create the method:
    public void delete(String tag, String name)
        ListNode list = xmlTree.getElementsByTagName(tag);
        System.out.pritln("SIZE LIST: " + list.getLength());
        for(int i = 0; i < list.getLength(); i++)
            System.out.println("NODE[" + i + "]: " + list.item(i));
            if(list.item(i).getNodeValue().equals(name))
                list.item(i).getParentNode().removeNode(list.item(i));
        }//End for
    }//End delete() methodThen I call :
    delete("name", "transformer2");And I get the result:
    SIZE LIST: 3 //Thats OK, I just had three nodes
    NOD[0]: null //Why I always get null, if the list had three nodes?!?!?
    NOD[1]: null
    NOD[2]: null
    Someone can help me??!? Thanks
    Giscard

    The value of an element is not the text that is inside the node. You would need to call
    getFirstChild, getNextSibling to collect the text, and then do the compare.

  • Stripping off XML tags

    Hi,
    Can someone help me with providing some code on how to strip off the XML tags in an XML file like the following:
    <?xml version = '1.0'?>
    <!--<?xml-stylesheet type="text/xsl" href="XYZ.xsl"?> -->
    <ROWSET>
    <ROW num="1">
    <PRODUCT_NAME>ABC</PRODUCT_NAME_NAME>
    </ROW>
    <ROW num="2">
    All I want to get back is whatever in between <product_name>. Basically, all the tags with <..> I need to get rid off from this XML file.
    Does anybody know if I can use regular expressions in java? That way, would it be easier not to use parsers?
    Please provide me ideas, sources, examples, etc.
    Thanks in advance.

    I worked on the solution, but, it's coming up with a blank list.
    Any solution to resolve this!
    Here's the code:
    public class Test extends JFrame
         JList list;
         JScrollPane listContainer;
         public Test()
              setSize(300, 300);
              setVisible(true);
              setTitle("ProdList");
              initialize();
         // domParse();     // Getting error- how do i call this function?
         public void initialize()
              list = new JList(new DefaultListModel()); // Set the initial model
              listContainer = new JScrollPane(list);
              listContainer.setSize(new Dimension(200, 200));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(listContainer, "Center");
              validate(); // Validate the screen
         // public void domParse(String url)
         public void domParse(String url)
              DocumentBuilder parser;
              DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
              try {
                        parser = factory.newDocumentBuilder();
                        Document doc = parser.parse(url);
              NodeList product_names = doc.getElementsByTagName("PRODUCT_NAME");
              if(product_names!=null)
              for(int i=0;i<product_names.getLength();++i)
                   // get all child nodes of a <product_name> - node
                   NodeList product_name_children=product_names.item(i).getChildNodes();
                   // and display contents of text nodes
              for(int j=0;j<product_name_children.getLength();++j)
                   Node node=product_name_children.item(j);
              //if(node.getNodeType()==Node.TEXT_NODE)
                   //System.out.println("element <"+product_names.item(i).getNodeName()+">'s text=["+node.getNodeValue()+"]");
              else
                   System.out.println("no element <PRODUCT_NAME> found");
              } catch (Exception e)
              // e.printStackTrace();
              static public void main(String[] args)
                   Test x=new Test();
                   x.domParse("Test.xml");

  • How to get only direct child node by tag name

    Hi,
    I am using the method
    getElementsByTagName("")....
    This works except the problem is my XML schema/file has some recursive tags,
    I have a <question> element which can have an <answer> or another <question>.
    When parsing the XML file I want to be able to get a list of sub questions for a given question, but only if it is a direct child of that question.
    So if i have:
    <question>
      <text>q1</text>
      <question>
        <text>q2</text>
        <question>
          <text>q3</text>
        </question>
      </question>
    </question>If I'm dealing with the "q1" question I want only "q2" but not "q3". Whereas getElementsByTagName will take both q2 and q3. How can I achieve this.
    Thanks

    You want only children and not other descendants? Then getChildNodes() and getFirstChild() and methods with similar names look like a good start.

  • CRLF not as text node

    How do I make the parser not to consider CRLF as text node?
    I'm having trouble using getFirstChild() method if I parse an XML that looks like
    <xml>
    <Animals>
    <Animal>
    </Animal>
    </Animals>
    </xml>
    The documentElement's(<xml>) firstChild expects to be <Animals>, but instead it is a text node which I believe is CRLF.
    If I rewrite the XML in one line (with no CRLF) then firstChild is <Animals> as expected.
    Any suggestion
    Thanks

    Hi the parser adds a TextNode for every new line (and even if you have only a space between two tags, it should be added) , this caused because the parser don't know if you want to read this information's.
    It's quite confusing, than normally you would expect this to be the node value, but it isn't!
    The node value by is normally null.
    See
    http://java.sun.com/j2se/1.4.1/docs/api/org/w3c/dom/Node.html
    for more information.
    Use getChildNodes and iterate trough them until you get a none TextNode.
    The NodeList knows:
    getLength()
    item (int)
    which is enough for a for loop.
    Or if you know the name of the child, you can use:
    getElementsByTagName(String name).item(0);
    Hope this helps.
    Greetings Michael

  • Error while System copy in Sapinist

    Hi All,
    i found an error while system copy ABAP + Java in SAPinist
    Error is
    CJS-00030  Assertion failed: in function (nothrow)
    {    NW.trace("NW.hasABAP(", nothrow, ")");    if (_hasABAP == undefined && !nothrow)
    {        ASSERT(arguments.callee, false, "NW(" + this.getSID() + ").hasABAP() is undefined");    }   
    NW.trace("NW.hasABAP() done: ", _hasABAP);    return _hasABAP;}NW(SAPID).hasABAP() is undefined
    ERROR 2010-09-24 10:52:45
    MUT-03025  Caught ESAPinstException in Modulecall: ESAPinstException: error text undefined.
    ERROR 2010-09-24 10:52:45
    FCO-00011  The step setLoadType with step key |NW_Prepare_Export|ind|ind|ind|ind|0|0|NW_GetSidFromProfiles|ind|ind|ind|ind|2|0|
    NW_getDBInfo|ind|ind|ind|ind|4|0|
    NW_getLoadType|ind|ind|ind|ind|0|0|setLoadType was executed with status ERROR .
    any body have solution
    gagandeep

    Hi,
    Please make sure the hostname is not beginning with digit?
    We found similar problem reported by other customers that the error occurs if hostname begginning with digit.
    For details, please refer to note  611361.
    If it is difficult for you to change hostname,  please stop sapinst and modify the control.xml in your
    installation directory:
    search for the string  pfdir.getChildNodes  and repleace the
    line
    for (var it =
    pfdir.getChildNodes(/^START_[A-Z0-9]+_[a-zA-z][a-zA-Z0-9-]*$/);
    !it.isDone(); it.next()) {
    with the line:
    for (var it = pfdir.getChildNodes(/^START_[A-Z0-9]+_[a-zA-Z0-9-]*$/);
    !it.isDone(); it.next()) {
    It is not sufficient to just restart SAPinst in order to fix the problem.
    You have to restart the installation from scratch with the modified control.xml.
    You can restart the installer from DVD, choose the installation service
    on the first screen, and when the next screen appears, interrupt the
    installer. Then patch the control.xml in the installation directory and
    restart the installer.
    Best Regards
    Julia

  • DOM Parser is ignoring condition .....

    Hi I am trying to parse this bit of code
         <Node>Call Setup
              <Condition>CallEvent
                   <Event>0</Event>
              </Condition>
              <Tariff>Fee
                   <Price>1.45</Price>
              </Tariff>
         </Node>
    But when I do getChildNodes
    and then getFirstChild
    it picks up tariff, and seems to ignore condition. Do I need to do something specific to read the condition node
    Thanks

    any ideas anyone?

  • Can I create my own NodeList?

    I'm using JDK1.4.0 and I'm using the DOM API to parse an XML file for me, and I'm calling methods like NodeList childNodes = parent.getChildNodes(), and such.
    However, due to the nature of XML, sometimes the child nodes are just "#text" nodes or "null". I wanted to write my own method to filter out these nodes and only keep the "good ones", but I don't see anything that would let me create build my own NodeList object, since Node and NodeList is just an interface.
    Most methods in the XML API want a NodeList object and not an ArrayList or some other container, so it's inconvenient to use something other than Node and NodeList.
    I tried tinkering with the implementing class of Node, which is IIOMutableNode or something close to this, but I got class cast exceptions during runtime.
    Thanks for any info.

    IIOMetadataNode, that's it.

  • XML reader and get the value from another class

    Hello to all, I have stupid question.
    I have main.java and ConfigXML.java(read my config xml file).
    Code from ConfigXML.java
    NodeList flnamelist = flcon.getElementsByTagName("filename");
    Element flnameEL= (Element)flnamelist.item(0);
    NodeList flnameTEXT = flnameEL.getChildNodes();
    String alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim();How I can get String alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim(); from my ConfigXML.java to main.java.
    Sorry for my bad english

    public class ConfigXML {
      private String alsl;
      // constructor goes here if necessary
      public void parse() {
        // something
        NodeList flnamelist = flcon.getElementsByTagName("filename");
        Element flnameEL= (Element)flnamelist.item(0);
        NodeList flnameTEXT = flnameEL.getChildNodes();
        alsl = ((Node)flnameTEXT.item(0)).getNodeValue().trim();
        // Notice that we assigned the data to an instance variable
      public String getAlsl() {
        return alsl;
    public class Main {
      // That's a really terrible name but at least let's capitalize it so it's standard
      public static void main(String[] args) {
        ConfigXML config = new ConfigXML();
        config.parse();
        String answer = config.getAlsl();
    }

  • Searching an XML file and using getNextSibling()

    I apologise if this question has been answered before, but I haven't been able to find a precise answer to my problem.
    Here is a snippet of my XML file:
    <organization...>
    <title>
    <item...>
    <title>
    <adlcp:prerequisites>
    What I want to do is search this file based on item title (org->item->title). When I find the corresponding entry, I want to traverse back up the tree to retrieve an attribute of the <item> tag, the <title> belonging to the organisation, and I also want to record the sibling node <adlcp:prerequisites>.
    I have no trouble obtaining traversing up the tree from the item <title>, but as soon as I try calling getFirstChild() or getNextSibling(), my method throws an exception.
    Here is an excerpt of my (somewhat shoddy) code:
    try
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
         docScorm = db.parse(strScorm);
         Element root = docScorm.getDocumentElement();
         NodeList children = root.getChildNodes();
         int n = children.getLength();
         String strTopicName = "";
         int i = 0 ;
         Node genericNode = null ;
         Node topicNode = null ;
         while(i < n)
              NodeList topicList = docScorm.getElementsByTagName("title");
              genericNode = topicList.item(i);
              strTopicName = genericNode.getFirstChild().getNodeValue();
              if (strTopicName.equals(strTopic))
                   topicNode = topicList.item(i) ;
              i++ ;
         //Save the information in the ScormInfo object.
         siItem.setTitle(strTopicName) ;
         //We have the topic name - get the other info.
         if (topicNode != null)
              Node itemNode = topicNode.getParentNode() ;
              NamedNodeMap nnmItemAtt = itemNode.getAttributes() ;
              Node itemIdentifierNode = nnmItemAtt.getNamedItem("identifier") ;
              //Fill in the ScormInfo object details.
              siItem.setIdentifier(itemIdentifierNode.getFirstChild().getNodeValue()) ;
    //I'd given up getting the organisation title, and settled for the identifier attribute instead.
    Node orgNode = itemNode.getParentNode() ;
              NamedNodeMap nnmOrgAtt = orgNode.getAttributes() ;
              Node orgTitleNode = nnmOrgAtt.getNamedItem("identifier") ;
              siItem.setOrganisation(orgTitleNode.getFirstChild().getNodeValue()) ;
              //Try to get the sibling.
              Node preReqNode = topicNode.getNextSibling() ;
    ====================================
    And this is the point where it all goes wrong. Can anyone shed some light on what I am doing wrong? Any help would be greatly appreciated.

    After a little more debugging, I discovered that you are correct - trying to access the Node is throwing a NullPointerException, and admittedly, I was not accounting for that.
    However, while I can easily take care of a NullPointerException, I am still bewildered as to why the getNextSibling function returns null in the first place. A quick snippet of the file in question shows:
    <organisation...>
    __<item identifier="ITEM-4E83F4CA-B846-67E5-48F1-C58732D13615" isvisible="true" identifierref="RES-74A66825-6926-3C1E-5D19-489856C9C280">
    ____<title>Topic_2_parallel_and_serial</title>
    ____<adlcp:prerequisites type="aicc_script">ITEM-5BE1806E-C38C-89A9-F2FC-BB51109259E3</adlcp:prerequisites>
    __</item>
    ====================================
    Considering my Node "topicNode" points to the "<title>Topic_2_parallel_and_serial</title> node, I am confused as to why getNextSibling does not return the <adlcp...> node. Is it not the next direct sibling?

  • Delete elements from XML file using DOM and java

    Hi
    I want now is to remove element from my XML file
    for example
    i have following xml
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
              <firstLineText />
              <firstLineText>|line11</firstLineText>
              <firstLineText>|line12</firstLineText>
    </firstLineTexts>
    </printing>how do i remove all elements fireLineText
    my final output should be
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
    </firstLineTexts>
    </printing>How do i do it using DOM,
    I can create instance of DOM and write it using TransformerFactory
    Ashish

    Hi
    I am trying the following code,
    but it is not working
                    NodeList nScene = doc.getElementsByTagName("firstLineTexts");
              NodeList nScene1 = nScene.item(0).getChildNodes();
              for (int i = 0; i < nScene1.getLength(); i++)
                   Node n = nScene1.item(i);
                        nScene.item(0).removeChild(n);
              }

  • Java XML and podcasts

    Hi all,,
    Im just looking for some help with a java xml passer program. Im trying to create a program that will read specific tags and the values that are represented by these tags in the xml file..I have found the following code
    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();
    Document doc = docBuilder.parse (new File("book.xml"));
    // 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 ();
    //System.exit (0);
    }//end of main
    }Im trying to develop this code to work with podcast xml files..Im having a few issuses with this program.. Is there anyone out there that has created a program like this that works with podcast xml files??
    Anyone got any suggestions.Please.

    XML and XSL transformations can be done using most languages and in Java there is strong support for these techniques.
    It worries me a little bit that you ask this question though. XML and XSL are no more than a tool to solve SOME problems, but I get the idea that you want to put them on your resume as if they are your main talent. The tool set of the developer is much broader than just some techniques to format and transform data, you need to be able to solve problems in the most efficient way possible, not limiting yourself to only a handful of techniques that you just happen to know a lot about.
    What I am trying to say is: it is always good to have knowledge of these techniques, but don't go thinking it is going to guarantee you a job.

  • Read in XML file and spit out specific element

    Hi all i wonder if someone could give me a hand. I've got some code (below) which reads in an xml file and spits out the contents of the file. Thats fine and dandy, however what i want to be able to do is specify which element to spit out, which i'm not sure how to do. So say i had the following xml file:
    <?xml version="1.0"?>
    <OpenSourceQuestions>
         <question>
              <setup>A raster graphics editor</setup>
              <answerChoice1>The Gimp</answerChoice1>
              <answerChoice2>The Chimp</answerChoice2>
              <answerChoice3>The Pimp</answerChoice3>
              <answerChoice4>The Blimp</answerChoice4>
              <correctAnswer>The Gimp</correctAnswer>
         </question>
         <question>
              <setup>test question 2</setup>
              <answerChoice1>question2 answer1</answerChoice1>
              <answerChoice2>question2 answer2</answerChoice2>
              <answerChoice3>question2 answer3</answerChoice3>
              <answerChoice4>question2 answer4</answerChoice4>
              <correctAnswer>question2 answer1</correctAnswer>
         </question>
    </OpenSourceQuestions>What i want to do is only spit out the xml for the first question, i.e. "A raster graphics editor" and its answers
    Here is my java code for reading in and arsing the file:
    void readXML(){
                try {
                     File fXmlFile = new File("MyXMLFile.xml");
                     DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                     Document doc = dBuilder.parse(fXmlFile);
                     doc.getDocumentElement().normalize();
                     System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
                     NodeList nList = doc.getElementsByTagName("question");
                     System.out.println("-----------------------");
                     for (int temp = 0; temp < nList.getLength(); temp++) {
                       Node nNode = nList.item(temp);
                       if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                         Element eElement = (Element) nNode;
                         System.out.println("Question : "  + getTagValue("setup",eElement));
                         System.out.println("Answer1 : "  + getTagValue("answerChoice1",eElement));
                         System.out.println("Answer2 : "  + getTagValue("answerChoice2",eElement));
                         System.out.println("Answer3 : "  + getTagValue("answerChoice3",eElement));
                         System.out.println("Answer4 : "  + getTagValue("answerChoice4",eElement));
                } catch (Exception e) {
                  e.printStackTrace();
               private static String getTagValue(String sTag, Element eElement)
                     NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
                     Node nValue = (Node) nlList.item(0);
                     return nValue.getNodeValue();
               }

    IN the time since i posted i have solved my own query!

  • Jax-ws 2.2.8 and ws-addressing: Client throwing java.lang.NullPointerException on receipt of HTTP 202 when using non-anonymous ReplyTo address

    Server: JBoss EAP 6.2.0
    Client: JDK 1.7.0_51 x64
    JAX-WS: RI 2.2.8 ( via -Djava.endorsed.dirs )
    I am getting a java.lang.NullPointerException when calling the operation on the WS endpoint from the client when using non-anonymous replyTo address.
    I have simplified the scenario into a small test case that hopefully others can replicate. Since the exception is happening on the client instead of the server, I would think that the container used is irrelevant, but I have specified it nonetheless.
    1) WebService:
    package test.webservice;
    import java.util.Random;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    import javax.xml.ws.soap.Addressing;
    @WebService(targetNamespace="http://services.nowhere.org/")
    @Addressing(required=true)
    @SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
    public class RandomTest {
        @WebMethod
        public long nextRandom(@WebParam boolean forceException) throws Exception {
            if( forceException ) {
                throw new Exception("Some exception");
            Random rand = new Random();
            return rand.nextLong();
    2) Generated WSDL by JBossEAP 6.2.2:
    <?xml version='1.0' encoding='UTF-8'?><wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:tns="http://webservice.test/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="RandomTestService" targetNamespace="http://webservice.test/">
      <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://webservice.test/" elementFormDefault="unqualified" targetNamespace="http://webservice.test/" version="1.0">
      <xs:element name="nextRandom" type="tns:nextRandom"/>
      <xs:element name="nextRandomResponse" type="tns:nextRandomResponse"/>
      <xs:complexType name="nextRandom">
        <xs:sequence/>
      </xs:complexType>
      <xs:complexType name="nextRandomResponse">
        <xs:sequence>
          <xs:element name="return" type="xs:long"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
      </wsdl:types>
      <wsdl:message name="nextRandom">
        <wsdl:part element="tns:nextRandom" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:message name="nextRandomResponse">
        <wsdl:part element="tns:nextRandomResponse" name="parameters">
        </wsdl:part>
      </wsdl:message>
      <wsdl:portType name="RandomTest">
        <wsdl:operation name="nextRandom">
          <wsdl:input message="tns:nextRandom" name="nextRandom" wsam:Action="http://webservice.test/RandomTest/nextRandomRequest" wsaw:Action="http://webservice.test/RandomTest/nextRandomRequest">
        </wsdl:input>
          <wsdl:output message="tns:nextRandomResponse" name="nextRandomResponse" wsam:Action="http://webservice.test/RandomTest/nextRandomResponse" wsaw:Action="http://webservice.test/RandomTest/nextRandomResponse">
        </wsdl:output>
        </wsdl:operation>
      </wsdl:portType>
      <wsdl:binding name="RandomTestServiceSoapBinding" type="tns:RandomTest">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsaw:UsingAddressing wsdl:required="true"/>
        <wsp:PolicyReference URI="#RandomTestServiceSoapBinding_WSAM_Addressing_Policy"/>
        <wsdl:operation name="nextRandom">
          <soap:operation soapAction="" style="document"/>
          <wsdl:input name="nextRandom">
            <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output name="nextRandomResponse">
            <soap:body use="literal"/>
          </wsdl:output>
        </wsdl:operation>
      </wsdl:binding>
      <wsdl:service name="RandomTestService">
        <wsdl:port binding="tns:RandomTestServiceSoapBinding" name="RandomTestPort">
          <soap:address location="http://localhost:8080/servertest/RandomTest"/>
        </wsdl:port>
      </wsdl:service>
        <wsp:Policy xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="RandomTestServiceSoapBinding_WSAM_Addressing_Policy"><wsam:Addressing><wsp:Policy/></wsam:Addressing></wsp:Policy>
    </wsdl:definitions>
    3) ant build.xml to generate the client code from WSDL
    <?xml version="1.0" encoding="UTF-8"?>
    <project default="build" basedir="..">
        <property name="jaxws.classpath" location="C://jaxws-2.2.8/jaxws-ri/lib/*.jar"/>
        <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
               <classpath path="${jaxws.classpath}"/>
        </taskdef>
        <target name="build" >
            <!-- For these to work, the JAR files in tools/jaxws-ri must be included in Ant's classpath -->
            <wsimport wsdl="http://localhost:8080/servertest/RandomTest?wsdl"
                   verbose="true"
                   sourcedestdir="src"
                   destdir="bin"
                   keep="true">
                   <xjcarg value="-enableIntrospection"/>
            </wsimport>
        </target>
    </project>
    4) Client code
    4a) ClientTest.java - Actual client run from client
    package test.wsclient;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.ws.BindingProvider;
    import javax.xml.ws.Endpoint;
    import javax.xml.ws.handler.Handler;
    import javax.xml.ws.soap.AddressingFeature;
    import org.nowhere.services.RandomTest;
    import org.nowhere.services.RandomTestService;
    public class ClientTest {
        public static void main(String args[]) throws Exception {
            ClientTest app = new ClientTest();
            app.testAddressing();
        public void testAddressing() throws Exception {
            String REPLY_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallback";
            String FAULT_TO_ADDRESS = "http://localhost:8082/servertest/RandomCallbackFault";
            RandomTestService service = new RandomTestService();
            RandomTest port = service.getRandomTestPort(new AddressingFeature());
            BindingProvider provider = (BindingProvider) port;
            // pass the replyTo address to the handler
            provider.getRequestContext().put("ReplyTo", REPLY_TO_ADDRESS);
            provider.getRequestContext().put("FaultTo", FAULT_TO_ADDRESS);
            // Register handlers to set the ReplyTo and FaultTo on the SOAP request sent to the WS endpoint
            List<Handler> handlerChain = new ArrayList<Handler>();
            handlerChain.add(new ClientHandler());
            provider.getBinding().setHandlerChain(handlerChain);
            // Start endpoint to receive callbacks from WS
            Endpoint endpoint = Endpoint.publish(REPLY_TO_ADDRESS, new CallbackSEI());
            try {
                port.nextRandom(false);
            } catch( Exception ex ) {
                ex.printStackTrace();
            } finally {
                Thread.sleep(10000);
            endpoint.stop();
            System.exit(0);
    4b) ClientHandler.java - Used to set the wsa ReplyTo address and FaultTo address when sending SOAP request from client to server
    package test.wsclient;
    import java.util.Set;
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.MessageContext.Scope;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class ClientHandler implements SOAPHandler<SOAPMessageContext> {
        public ClientHandler() {};
        @Override
        public Set<QName> getHeaders() {
            return null;
        @Override
        public void close(MessageContext arg0) {
        @Override
        public boolean handleFault(SOAPMessageContext context) {
            return true;
        protected void setAnAddress(SOAPHeader header, String tagName, String address) {
            NodeList nodeListReplyTo = header.getElementsByTagName(tagName);
            NodeList nodeListAddress = nodeListReplyTo.item(0).getChildNodes();
            for (int i = 0; i < nodeListAddress.getLength(); i++) {
                Node node = nodeListAddress.item(i);
                if ("Address".equals(node.getLocalName())) {
                    node.setTextContent(address);
                    break;
        protected String getMessageID(SOAPHeader header) {
            NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
            return nodeListMessageId.item(0).getTextContent();
        @Override
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean isOutbound = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (isOutbound) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPHeader header = envelope.getHeader();
                    /* extract the generated MessageID */
                    String messageID = getMessageID(header);
                    context.put("MessageID", messageID);
                    context.setScope("MessageID", Scope.APPLICATION);
                    /* change ReplyTo address */
                    setAnAddress(header, "ReplyTo", (String) context.get("ReplyTo"));
                    setAnAddress(header, "FaultTo", (String) context.get("FaultTo"));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
            return true;
    4c) CallbackSEI.java - endpoint on the client for server to send the SOAP response back to the client
    package test.wsclient;
    import javax.annotation.Resource;
    import javax.jws.Oneway;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.ws.Action;
    import javax.xml.ws.RequestWrapper;
    import javax.xml.ws.WebServiceContext;
    import javax.xml.ws.soap.Addressing;
    @WebService
    @Addressing
    //@HandlerChain(file = "/handler-chain.xml")
    public class CallbackSEI {
        @Resource
        private WebServiceContext context;
         * If there is no namespace specified in the method below, then the CallbackSEI needs to be in the same package as the
         * WS endpoint.
        @Oneway
        @Action(input="http://services.nowhere.org/RandomTest/nextRandomResponse")
        @RequestWrapper(localName="nextRandomResponse", targetNamespace="http://services.nowhere.org/")
        public void handleNotification(@WebParam(name="return")long random) {
            System.out.println("Asynch response received");
            System.out.println( random );
            //System.out.println("This response relates to the message ID: "+ getMessageID());
    In summary:
    Server is listening on port 8080
    Client will listen in port 8082 for the callback from the server for the SOAP response
    Now when I run the client, I see that the proper behaviour as far as ws-addressing is concerned. That is:
    client  -- SOAP request ( on port 8080 ) --> server
    client <-- HTTP 202 ( empty HTTP body )  --- server
    client <-- SOAP response ( on port 8082 )  --- server
    All well and good, except that I am getting a NullPointerException on the client side when I call the operation.
    With debugging of the SOAP request and responses, I get the following output:
    ---[HTTP request - http://localhost:8080/servertest/RandomTest]---
    Accept: text/xml, multipart/related
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://services.nowhere.org/RandomTest/nextRandomRequest"
    User-Agent: JAX-WS RI 2.2.8 svn-revision#13980
    <?xml version='1.0' encoding='UTF-8'?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><S:Header><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8080/servertest/RandomTest</To><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomRequest</Action><ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallback</Address>
    </ReplyTo><FaultTo xmlns="http://www.w3.org/2005/08/addressing">
        <Address>http://localhost:8082/servertest/RandomCallbackFault</Address>
    </FaultTo><MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</MessageID></S:Header><S:Body><ns2:nextRandom xmlns:ns2="http://services.nowhere.org/"><arg0>false</arg0></ns2:nextRandom></S:Body></S:Envelope>--------------------
    ---[HTTP response - http://localhost:8080/servertest/RandomTest - 202]---
    null: HTTP/1.1 202 Accepted
    Content-Length: 0
    Content-Type: text/xml;charset=UTF-8
    Date: Fri, 18 Jul 2014 08:34:36 GMT
    Server: Apache-Coyote/1.1
    java.lang.NullPointerException
        at com.sun.proxy.$Proxy38.nextRandom(Unknown Source)
        at test.wsclient.ClientTest.testAddressing(ClientTest.java:43)
        at test.wsclient.ClientTest.main(ClientTest.java:18)
    ---[HTTP request]---
    Cache-control: no-cache
    Host: localhost:8082
    Content-type: text/xml; charset=UTF-8
    Content-length: 704
    Connection: keep-alive
    Pragma: no-cache
    User-agent: Apache CXF 2.7.7.redhat-1
    Accept: */*
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><Action xmlns="http://www.w3.org/2005/08/addressing">http://services.nowhere.org/RandomTest/nextRandomResponse</Action><MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:65d8d7fc-09e4-494a-a9c5-0a01faf4d7e6</MessageID><To xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8082/servertest/RandomCallback</To><RelatesTo xmlns="http://www.w3.org/2005/08/addressing">uuid:bcd2f6ef-3034-49e8-b837-dbd6a772fb93</RelatesTo></soap:Header><soap:Body><ns2:nextRandomResponse xmlns:ns2="http://services.nowhere.org/"><return>2870062781194370669</return></ns2:nextRandomResponse></soap:Body></soap:Envelope>--------------------
    Asynch response received
    2870062781194370669
    As you can see from the output above, the proxy is throwing an Exception when it receives the HTTP 202 response.
    Any ideas ?

    I think I have found when I get this error and probably I have found a bug. I will appreciate if someone can confirm this.
    In my BPEL project setup, my BPEL process's wsdl file imports another wsdl from different namespace. Here is sample snippet -
    <wsdl:definitions targetNamespace="http://namespace/1">
    <wsdl:import namespace="http://namespace/2" location="resources/another.wsdl"/>
    <plnk:partnerLinkType....../>
    </wsdl:definitions>
    Please let me know. I checked the bundled samples with Oracle BPEL PM and did not find any similar case where process wsdl imports another wsdl.
    Thank you.
    Meghana

  • Append data and save in XML

    hi all ! I have some data that is stored in a XML fine and since each SML is client based it can be edited according to everyone tastes. So my question is, can someone point me out how to append data and then saving it into the XML (hopefully without having to rewrite the whole XML document.
    This is how Im retreiving my Data from the XML and my try at appending data, but I dont know if Im being succesfull because its not being saved:
    String path = "C:/MedPro";
                    File file = new File(path + "/XML/data.xml");
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(file);
                    doc.getDocumentElement().normalize();
                    /* PARA ALIMENTAR LA AGENDA CON LOS DATOS DEL XML*/
                    NodeList nodeLst = doc.getElementsByTagName("Agenda"); //Lista de Items para manejar la agenda
                    for (int s = 0; s < nodeLst.getLength(); s++) {
                        Node fstNode = nodeLst.item(s);
                        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element fstElmnt = (Element) fstNode;
                            NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("sub");
                            Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                            Node nod=fstNmElmntLst.item(0).appendChild(doc.createTextNode("Hola"));
                            /*NodeList fstNm = fstNmElmnt.getChildNodes();
                            System.out.println("Agenda : " + ((Node) fstNm.item(0)).getNodeValue());
                            lista_agenda.add(s, ((Node) fstNm.item(0)).getNodeValue());*/
                    }Any help is appreciated.
    Thanks a lot!
    Edited by: juanmanuelsanchez on Oct 10, 2009 4:27 PM

    juanmanuelsanchez wrote:
    ok but is there a way to do it without having to rewrite the whole XML?short answer, no. xml, like many structured file formats, is not really amenable to "partial updating". the only way to "append" data to a file without rewriting it is to write to the end of the file. how will you maintain a valid xml format by only adding to the end of the file? i can't imagine the xml is that large seeing as you are using a DOM parser to read it, so i don't understand why you don't want to just rewrite the file.

Maybe you are looking for