My XML file is in the following format:
<top>
<name></name>
<title></title>
<time></time>
</top>
<top>
...
</top>
<top>
...
</top>
I write the following code to read the xml file:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(QUERY_FILE)); //LINE (*)
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("top");
But the problem is I get error as at line (*):
The markup in the document following the root element must be
well-formed.
It seems that error is because I have multiple root elements in the xml file. One solution could be I add maybe <doc></doc> outside all <top> elements. But is there any other way that I can directly read in such XML file as element arrays?
You can try to isolate each<top> element and trying to parse them separately, but that's a more troublesome solution than just wrapping <doc></doc> around the xml content..
One thing I've done in the past is instead of putting the root tags in the file itself, I just read the text into a string, and wrap the <doc></doc> tags around the string before I load the XML.
You are add this line for well-formed :
<?xml version="1.0" encoding="UTF-8"?> <!-- this line-->
<top>
<name></name>
<title></title>
<time></time>
</top>
Use this page to see if your document is correct, since it is the one that sets the standard for this metalanguage.
http://validator.w3.org/#validate_by_input
Validate xml dtd, etc ..
The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web (abbreviated WWW or W3).| Font Wikipedia
Related
I am receiving following XML response via Jersey client
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><aaa><bbb key="Data"><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<my-data xsi:noNamespaceSchemaLocation="MyData.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<data name="abc" uniqueId="4fe95637-a381-4e0c-bf7f-49f794df5f23">
<variable var1="xyz" value="44"/>
</data>
</my-data>
</bbb></aaa>
I am saving this as an XML file and getting 'premature end of file' error during parsing, since the XML is malformed (duplicate XML declarations)...is there a way to remove following duplicate entry from the output?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Following is my Java code snippet:
String output = response.getEntity(String.class);
file = writeResponseToFile(output,"MyData.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file); //Error
Ideally, you should fix the problem at the source. What you're receiving is not XML because having more than one XML declaration violates XML's basic grammar, making the data not well-formed.
If it is impossible to properly fix the problem at the source, and you wish to attempt repair, you have to treat that data as text, not XML, until you remove the extra XML declaration (via text-level operations, not XML parsing).
Fix the xml that you are receiving. You receive two declarations in the xml.
The xml is malformed. Remember in Jersey, you can receive files on JSON, xml, html, etc, via annotations, with #Produces.
And remember that you have xml validators on internet, to valid your xml.
Regards.
I am trying to create an org.w3c.dom.Document object from an xml string. I have followed what many have suggested in other questions but the document ends up empty. What is wrong with the following code?
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(response.getResponseText())));
And the xml text in the string looks like the following (this comes from response.getResponseText())
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://www.blah.com/ns/2006/05/01/webservices/123/TokenManagement_1/CreateServiceToken_1_Reply</a:Action>
<CacheResponse xsi:type="DoNotStoreCacheResponse" xmlns="http://www.blah.com/ns/2008/03/01/webservices/123/Cache_1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Date>2012-09-04T15:35:06.8116593Z</Date>
<DoNotStore />
</CacheResponse>
<a:RelatesTo>ba04425d-d93e-4a70-a134-ab8e29d5345c}</a:RelatesTo>
</s:Header>
<s:Body>
<CreateServiceToken_Response_1 xmlns="http://www.blah.com/ns/2006/05/01/webservices/123/TokenManagement_1" xmlns:global="http://www.blah.com/ns/2006/05/01/webservices/123/Common_1">
<Expiration>2012-09-04T17:04:19.1834228Z</Expiration>
<global:Token>3DEC2723A01047D1590544CBA5BA1E30326535E609DC1E6FAC5C659BC3B8A693BB054834A58B235037ED830CD05784DB176A62309AEB4B608C6F0B5B3F13ADE0EC56BE9F822ACFA3B549D4427D89BF030BFF48BA671DCAEB49940EFEBDEBFB71</global:Token>
</CreateServiceToken_Response_1>
</s:Body>
Can anyone see what is wrong with my code? I ultimately just want to run a couple of xpath queries on the document...
I would suggest to start with setting docFactory.setNamespaceAware(true);, otherwise the parsing, the DOM built and the XPath implementation will not be able to work with XML with namespaces as you have posted.
I am really new to XML and JDOM so I have a noob question, sorry for that. I have a XML file and I want to insert value into it. My XML file is like that;
<?xml version="1.0"?>
<message>
<header>
<messageType> </messageType>
<sendFrom> </sendFrom>
<HostName> </HostName>
<sendTo> </sendTo>
<receiverName> </receiverName>
<date> </date>
</header>
<body>
</body>
</message>
So what I want is for example is to add value between <sendTo> </sendTo> and also I want to add <A> data </A> between <body> </body>. Can you please tell me how to do that ?
Thanks a lot.
http://www.cafeconleche.org/books/xmljava/chapters/ch14s04.html
http://www.java2s.com/Code/Java/XML/MakeupandwriteanXMLdocumentusingDOM.htm
If you use dom,you can do it as follows;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
Node messageType= doc.getElementsByTagName("messageType").item(0);//zero tells the order in the xml
messageType.setTextContent("SMS");
I'd recommend using XStream for XML handling.
Here, is the link to a 2 minute tutorial: http://x-stream.github.io/tutorial.html
I want to copy an node to a different Documentg, but it always has DOMException about
org.apache.harmony.xml.dom.NodeImpl.setNameNS(NodeImpl.java:227)
here is my code
private String getString(Node seqNode) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("Test");
doc.appendChild(root);
/* following line will cause DOMException */
doc.importNode(seqNode, true);
...
...
} catch (Exception e) {
}
}
where seqNode belongs to other Document
does any body has idea about this issue? :-)
I ran into this problem too. I was getting this exception when calling either importNode() or cloneNode(). And BTW, the XML I was parsing/generating was not using namespaces.
It seems that the DOM parser (from Apache Harmony) that is included in Android is buggy. See this link: Issue 2735: Harmony DOM implementation is buggy and noncompliant. Everything works fine if the same code is executed using plain Java 1.6 (which isn't based on Harmony of course).
I tried setting setNamespaceAware(true) on the DocumentBuilder, but this did not help.
Eventually, I gave up and worked around the issue by using adoptNode() rather than importNode(). This is kind of incestuous, because it is stealing a node from one Document tree and putting it into another. But in my case, the first Document tree was only temporary, so I could do things this way.
I'm guessing, but it seems that you are trying to import node with namespace defined, where your target document does not have this namespace declared.
So, what namespaces are declared in source document? Did you declare any namespaces in target document?
The input is a smil String shown below:
<smil>
<head>
<layout>
<root-layout height="720" width="1280"/>
<transition id="fade" type="fade" subtype="crossfade" dur="1s"/>
<region id="_33_32_bkgd_image" left="0" top="0" width="1280" height="720" background-color="#c12121" showBackground="whenActive" z-index="0"></region>
<region id="_33_32_I001" left="380" top="27" width="405" height="352" z-index="1"></region><region id="_33_32_I002" left="0" top="365" width="354" height="354" z-index="2"></region>
</layout>
</head>
<body>
<seq begin="wallclock(2011-09-22T01:52:00)" end="wallclock(2011-09-23T00:00:00)">
<par dur="10s" xml:id="32" repeatCount="1">
<brush color="#c12121" region="_33_32_bkgd_image"></brush>
<seq repeatCount="indefinite">
<img xml:id="30" region="_33_32_I001" src="http://127.0.0.1/Service/User/2_user/Media/Image/30_image.jpg?JFBukihsTu" dur="5s" fit="meet" regPoint="center" regAlign="center">
<metadata xml:id="meta-rdf">
<meta name="MD5" content="7c8b59b28ea2247f20bc538dcb7108f3"></meta><meta name="width" content="531"></meta><meta name="height" content="720"></meta></metadata></img>
<img xml:id="27" region="_33_32_I001" src="http://127.0.0.1/Service/User/2_user/Media/Image/27_image.jpg?jTqCMuIxsX" dur="5s" fit="meet" regPoint="center" regAlign="center">
<metadata xml:id="meta-rdf">
<meta name="MD5" content="db51409f243f79c566811d1b307a77a1"></meta><meta name="width" content="427"></meta><meta name="height" content="602"></meta></metadata></img>
</seq>
</par>
</seq>
</body>
</smil>
and the original Document is generated by:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new ByteArrayInputStream(smil.getBytes()));
and the seqNode represents the "seq" node (the child of body tag)
I want to copy "seq" and all of it's childs to new Document
I'm writing an XML file to the sd card, and I need to be able to open that XML file and append data to it. How can I accomplish this? For example, my XML file is:
<items>
<item attr="value">data</item>
<item attr="value2">data 2</item>
</items>
I later need to open this XML file and append a new item to it:
<item attr="value3">data 3</item>
How can I do this?
You can use a sax parser that reads the file, outputs all elements by default and when it finds the closing {}, first insert the new item, then the closing tag.
Sax parsers are available by default in Android.
One example on how to deal with Sax at all can be found here.
What you want is to obtain a Document class version of your XML file. You can do this using a DOM Parser. From the Document class you can then manipulate it and write it back out with your modifications.
Here's code on DOM parsing.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(myfilepath);
More information on different approaches to XML in Android can be found here.