Parsing from a string of XML?

Hi there,
I'm using DOM to parse some XML. However, the XML is not in a file, it's in a String. So the DocumentBuilder's parse(...) method takes an InputStream or File object but I'm looking to parse a String. Can anybody help me??
Cheers,
Sean

Ok I found out a way to parse an XML string:
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xmlString.toString());
InputSource is = new InputSource(sr);
document = builder.parse(is);
But I'm getting the following error on the parse() line:
[Fatal Error] :1:20: A pseudo attribute name is expected.
org.xml.sax.SAXParseException: A pseudo attribute name is expected.
     at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
     at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
     at test.TestDOM.main(TestDOM.java:61)
The XML string is:
String xmlString = "<?xml version=\"1.0\"><tag><tag_id>250397</tag_id><reader_id>1</reader_id><rssi>74</rssi><date>7/19/2006</date><time>2:59:47 PM</time></tag>";
Can anybody help?
Cheers,
Sean

Similar Messages

  • XML Parsing From A String (Not a File)

    Hi all,
    I've been looking throughout this forum and still can't find a total answer to my question. I was wondering if it is possible to do the following:
    I want to pass in a string of XML code to a java stored procedure; the XML string looking like the following (for example):
    <Table-Name="PersonalInfo">
    <row>
    <First-Name>Bob</First-Name>
    <Last-Name>Smith</Last-Name>
    <Age>55</Age>
    </row>
    </Table-Name>
    We don't want to be passing in an XML file; we want to pass in the actual string of XML code that would be in the file.
    Is it possible to put into the DOM format (like every example I've seen so far) by parsing an XML formatted string? If so, how would I go about doing that?
    Thanks in advance!
    Jadie

    <Table-Name="PersonalInfo">
    <row>
    <First-Name>Bob</First-Name>
    <Last-Name>Smith</Last-Name>
    <Age>55</Age>
    </row>
    </Table-Name>This is exactly what JAXB is for! :)
    With JAXB unmarshalling against an XSD file can be applied to any InputStream, etc.
    Take a look at JAXB, and you'll find it'll be just what you're looking for. :)
    In fact, here's a short segment of the XSD you'd write for the above:
    <xsd:complexType name="PersonalInfo">
    <xsd:sequence>
    <xsd:element name="row" type="PersonalInfoRow" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="PersonalInfoRow">
    <xsd:sequence>
    <xsd:element name="First-Name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
    <xsd:element name="Last-Name" type="xsd:string" minOccurs="1" maxOccurs="1"/>
    <xsd:element name="Age" type="xsd:int" minOccurs="1" maxOccurs="1"/>
    <xsd:sequence>
    </xsd:complexType>
    Also, perhaps redesign your XML a little, since each table will be different, simply use its name as the tags...i.e. <PersonalInfo></PersonalInfo> and change the <row> to <PersonalInfo> since <row> is pretty generic and will probably occur many times in other places.
    Hope this helps you along your way. :)
    -G

  • Parsing XML from a String

    I have a servlet, this recieves an XML file from the client as a file input type from a html form. This XML is wrapped up in http headers and stuff. I parse the input stream from the client's http request to get a string containing the xml. This is fine.
    How do I now build an XML document from this string? The DocumentBuilder will take in files and InputStreams but I can't find anything that helps me?
    The only solution I've come up with is to write out the string to a temp file and then parse it back into a Document.
    Any ideas anyone?????

    Document doc = documentBuilder.parse(new InputSource(new StringReader(yourXMLString)));
    voila!

  • How to create an XML document from a String.

    Can anyone help,
         In the Microsoft XML Document DOM there is a load function load(string) which will create an XML document, but now we are switching to Java and I do not know how to create and XML document from a string, this string �xml document� is passed to my program from a webservice and I need to read several xml elements form it in a web server.
    This string is a well formatted XML document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Countries NumberOfRecords="1" LanguageID="en-us">
         <Country>
              <CountryCode>AU</CountryCode>
              <CountryName>AUSTRALIA</CountryName>
         </Country>
    </Countries>

    Thanks PC!
    I made it work using:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    factory.setIgnoringComments(true); // We want to ignore comments
    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();
    //TransformThisStringBuffer is a string buffer wich contain the 'XML document (String)'
    InputStream in = new ByteArrayInputStream(TransformThisStringBuffer.toString().getBytes());
    // Parse the InputStream and build the document
    Document document = parser.parse(in);
    But which one is faster InputSource or InputStream, were would you put the "new InputSource(new StringReader(yourString))" in the above code?

  • How do I create individual xml files from the parsed data output of a xml file?

    I have written a program (DOM Parser) that parses data from a XMl File. I would like to create an individual file with the corresponding name for each set of data parsed from the xml document. If the parsed output is Single, Double, Triple, I would like to create an individual xml file (Single.xml, Double.xml, Triple.xml)with those corresponding names. How do I create the xml files and give each file the name of my parsed data output? Thanks in advance for your help.
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println("Template" + ": " +templateElement.getAttribute("name")+ ".xml");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

    Ive posted the new code but now I'm getting a FileAlreadyExistException error. How do I handle this exception error correctly in my code?
    import java.io.IOException;
    import java.nio.file.FileAlreadyExistsException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    public class MyDomParser {
      public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse("ENtemplate.xml");
      doc.normalize();
      NodeList rootNodes = doc.getElementsByTagName("templates");
      Node rootNode = rootNodes.item(0);
      Element rootElement = (Element) rootNode;
      NodeList templateList = rootElement.getElementsByTagName("template");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      System.out.println(templateElement.getAttribute("name")+ ".xml");
      for(int i=0; i < templateList.getLength(); i++) {
      Node theTemplate = templateList.item(i);
      Element templateElement = (Element) theTemplate;
      String fileName = templateElement.getAttribute("name") + ".xml";
      Files.createFile(Paths.get(fileName));
      System.out.println("File" + ":" + fileName + ".xml created");
      } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

  • JAXB: Read XML data from a String?

    Hi,
    I get XML data not from file but as a string and I wanted to use JAXB to parse it and get my Java Objects.
    The unmarshall methods wants an "InputStream", but "StringBufferInputStream" is deprecated, so that I don't know a way to use my String as InputStream.
    Can someone give me a hint other then writing the data in a file first?

    Hi FrankSch,
    The unmarshall methods wants an "InputStream", but
    "StringBufferInputStream" is deprecated, so that I
    don't know a way to use my String as InputStream.
    Can someone give me a hint other then writing the data
    in a file first?Yes, the class StringBufferInputStream is deprecated, and the deprecation notice reads:
    Deprecated. This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.
    The JDK API usually mentions an alternative to the deprecated method/class and in this case, you should use java.io.StringReader. It has one constructor and should suite you nicely:
    StringReader(String s) That way, you get an InputStream object; you can now use JAXB.
    Hope this helps,
    -ike, .si

  • How to decode a base64 image that is parsed from an xml

    Hi everyone,
    I'm trying to decode a base64 image that is parsed from an XML. I was able to decode everything except for an image, and it resulted in weird characters such as
    ������?��������?��������f����������?
    I used sun.misc.BASE64Decoder()
    Thanks in advance,
    Squid

    Hi,
    I know that those are wierd characters because I have the correctly decoded data, and it looks different. Does any one know how to decode against the ASCII
    I know the following code would decode my base64 image correctly, but i dont know how to do the same in java for the follwing C# line of code:
    System.Web.HttpUtility.UrlDecode(sXMLString,
    System.Text.Encoding.GetEncoding(1252));
    Below is the entire C# code that successfully decode the base64 image from " test9.xml"
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Web;
    namespace DecodeXML
    class Program
    static void Main(string[] args)
    string sFileName = "test9.xml";
    string sXMLString = File.ReadAllText(@"C:\NET 2.0 Projects\ThrowAways\SampleLabels\" + sFileName);
    string resultString =
    System.Web.HttpUtility.UrlDecode(sXMLString,
    System.Text.Encoding.GetEncoding(1252));
    XmlDocument oXML = new XmlDocument();
    oXML.LoadXml(resultString);
    XmlNode oLabel = oXML.SelectSingleNode("//LabelBody");
    // removed the line that saved it to a string variable, because it converts the binary characters to
    // incorrect text representations. However, by saving the bytes directly rectifies this
    File.WriteAllBytes(@"C:\NET 2.0 Projects\ThrowAways\SampleLabels\" + sFileName + ".txt", Convert.FromBase64String(oLabel.InnerText));
    Any suggestion is strongly appreciated.
    Thanks,
    Squid

  • XML string to XML parsing in JCD

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
    Kindly suggest a way to achieve this.

    An XSD OTD has an unmarshalFromString() method:
    inputFormat.unmarshalFromString( strData );
    When putting the XML into the CLOB it could be a good idea to wrap an outputstream into a Writer object in order to make certain that the encoding is correct, depending how the data is represented. When retrieving CLOB data using getCharacterStream() you will get a Reader object where the encoding is already given.

  • How to parse a string containing xml data

    Hi,
    Is it possible to parse a string containing xml data into a array list?
    my string contains xml data as <blood_group>
         <choice id ='1' value='A +ve'/>
         <choice id ='2' value='B +ve'/>
             <choice id ='3' value='O +ve'/>
    </blood_group>how can i get "value" into array list?

    There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
    Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf.                                                                                                                                                                                                                                                                                                                                                                                                               

  • Parseing a Float from a string.

    Does anyone know how to parse a float from a string variable? The documentation says there is a method for it, it doesn't say what it is(?).
    I.e. the equavilent of int this_num.parseint(this_string) only for a float.
    Thanks.

    Thanks, that helped...now for another apparently stupid question....
    How do you add two floats??
    I have:
    fInvAmount = fInvAmount + Float.parseFloat(rsSmartStreamInvoice.getString("invoice_amt"))
    and it tells me that 'operator + cannot be applied to java.lang.Float,float'

  • How to parse out curly quotes from a string

    Hi,
    I am writing a web application, where people will be copying from a Word Document into a text area. Then I get a String from the parameter passed.
    How can I parse out curly quotes and mdashes from this String? Are there specific character codes that I can parse out to replace them with regular quote characters or html quote characters?
    Thanks,
    Gabe

    Interesting problem and one that we had to deal with a couple of years ago. I think you might be talking about smart quotes and these are actually control characters used by MS products. They show up as squares in HTML unless properly dealt with. Try downloading some UNICODE charts to find out the values of these characters. I think they are something like 0044 and 0042 but I cannot remember off hand.

  • XML String to XML Parsing

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD in JavaCAPS using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
    Kindly suggest a way to achieve this.

    The forum itself is a good starting point : [http://forum.java.sun.com/thread.jspa?forumID=34&threadID=347151] is a result searching for "parse string"...

  • Parsing string to xml

    Dear All,
    I have an OSB service which returns an xml form of output in string.
    I am calling this OSB service in BPEL but it fails due to this string format recieved by BPEL.
    How can I avoid it. I am also trying to convert string to xml but failing to do so.
    Any pointers to this would be helpful
    Thanks and Regards,
    Mits

    try setting the Outbound Response HTTP transport header
    http:Content-Type=text/xml
    or application/xml (even better)
    (and of course you should make sure you have fn-bea:inlinedXml() function to turn the String into a XmlObject)

  • From string to XML

    Hi,
    How can i convert a string to XML so i can use it's tags?

    sergei_developer wrote:
    you have to use :
    var x:XML =<info><titel>blaaaaaaat</titel></info>;
    var s:String = x.info.@title;
    That code is incorrect and it won't work. "titel" is not an attribute but a node so you should access it that way and also, the root node ( called "info" ) is considered implicit, which means that you would access the "titel" node this way: var s:String = x.titel;
    Good luck,
    Barni

  • String to XML

    Hi everyone,
    i'm just writing a method, that gets a string and a XPath and want writes the string to the specific XPath in my xml document. The problem ist, that the string itself can contain nodes like (e.g. <image> or something else from my dtd, so i got some problems converting the string to xml. Actually i'm trying this:
         public static void setEditFragment(String content, String xPath) throws Exception {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder  = factory.newDocumentBuilder();
             Document document = builder.parse("data.xml");
             XPath xpath = XPathFactory.newInstance().newXPath();
             Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
             System.out.println(content);
             node.setTextContent(content);
             // Use a XSLT transformer for writing the new XML file
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                // Set output to IsoLatin1
                transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
             DOMSource        source = new DOMSource( document );
             FileOutputStream os     = new FileOutputStream("tmp.xml");
             StreamResult     result = new StreamResult( os );
             transformer.transform( source, result ); 
         }but of course this will not work and sets up some cryptic signs in mein xml document....
    can anyone give me advice ?
    Thanks !

    Well, if you already have the data XML encoded, then just write them to a file:
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    Make sure you encode the data with UTF8:
    http://java.sun.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)
    Write "<?xml version="1.0" encoding="utf-8"?>" before the data!
    Note however, I generally don't recommend to write XML data by hand. Rather use a framework like JAXB.
    -Puce
    Edited by: Puce on May 8, 2008 1:36 PM

Maybe you are looking for

  • PLSQL portlet - problem calling stored procedure -

    Good day folks. My portal version 10.1.2. I have a dynamic page with multiple rows. For simplicity, example here has two columns => id and value. The initial dilemma - The stored procedure specified in the action attribute of the <form> tag has to ha

  • HT201441 Hi I need activate code for iPhone 5

    Hi I got iPhone 5 remoove old active code please help

  • Reg : User Exit for IA05 - Operation Overview

    Hi Team, I have a requirement in IA05 in the operation overview we have a field called Std Text field(PLPOD-KTSCH) , Where the user gives the text field in the screen, So based on the text key i need to populate  work,duration, in the same screen as

  • Updating BIOS, Windows won't run the exe

    I'm running Win7 Pro x64 and I want to update the BIOS on a a55m-p33 mobo. Live update just says 'download fail', so I've downloaded the file separately and put it on a pen drive as per the BIOS Update SOP. When I run the exe it says it isn't compati

  • Uble to install IM for Nokia - Chat on the go on ...

    I tried to install this and got the error 2148532241 on Ovi Suite. What should i do? I restored the phone to it's original settings by *#7370* code but still no luck...