I am trying to write an xml file using Java and I want to send a variable string to the method document.createElement(var) ,but it gives me that error:
"Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(Unknown Source)
at eg.edu.alexu.csd.oop.draw.WriteXML.<init>(WriteXML.java:47)
at eg.edu.alexu.csd.oop.draw.Test.main(Test.java:25)"
this error because var is a variable
public class WriteXML {
public WriteXML() throws FileNotFoundException, ParserConfigurationException, IOException{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
for(int i=0 ; i<shapes.length ; i++){
//class
s = shapes[i].getClass().getName().toString();
Element rootElement = xmlDoc.createElement(s);
}
A number cannot be used as a tag name. Here is a simplified test:
// Generates the error
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("0");
You can use an attribute, or text content, to set the number.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("Red").setTextContent("0");
XML Specification
I am not sure, but I think the related line is:
[Definition: A Name is an Nmtoken with a restricted set of initial characters.] Disallowed initial characters for Names include digits, diacritics, the full stop and the hyphen.
Related
I want get RECORD number based on contract id passed to java method. can any one help on this as i am new to XML parsing?
sample xml file:
<?xml version="1.0"?><FILE>
<Document RECORD="1"><Contract-Id>234</Contract-Id><Client-Id>232</Client-Id></Document>
<Document RECORD="2"><Contract-Id>235</Contract-Id><Client-Id>334</Client-Id></Document>
</FILE?
Java code:
File fXmlFile = new File(inputFile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xmlDocument = dBuilder.parse(fXmlFile);
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpr = xPath.compile("//Document/Contract-Id[text()='"+ContractNumber+"']");
//Object result = xPathExpr.evaluate(xmlDocument,XPathConstants.NODESET);
Node nl = (Node)xPathExpr.evaluate(xmlDocument.getParentNode(), XPathConstants.NODESET);
nl.getTextContent();
nl.getAttributes();
Please try the following XPath expression:
/FILE/Document[Contract-Id="235"]/#RECORD
I have converted a string to an XML document using the code below:
String xmlStr = "<msg><uuid>12345</uuid></msg>"
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
return doc;
} catch (Exception e) {
throw new RuntimeException(e);
}
Then I converted an XML file to a document with the following:
File file = new File("src/test/resources/xmlForJunitTest.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document expectedDoc = db.parse(file);
Finally I compare the two documents:
Document actualDoc = XmlUtils.convertStringToDocument(xmlString);
Diff myDiff = new Diff(expectedDoc, actualDoc);
assert (myDiff.similar());
This test passes using an XML file (xmlForJunitTest.xml) formatted like so:
<msg><uuid>12345</uuid></msg>
And it fails with this:
<msg>
<uuid>12345</uuid>
</msg>
Please you can suggest why this failure occurs, and what the solution is?
The assertion fails because one document includes whitespace, and the other doesn't. I believe you need to look at the normalizeWhitespace flag in XmlUnit (assuming that's what you're using).
I am appending text to XML element iteratively like the following
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File("./myXML.xml")));
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName("name");
Element fn= (Element) node1.item(0);
Text text = doc.createTextNode(Content);
fn.appendChild(text);
printtoXML(doc);
My printXML method is updating xml by using TransformerFactory
fn.setTextContent() method does not work here,Because in every iteration it setting old text to new text.
I want to append Text iteratively, and in my next execution i want to delete old text contents of the particular element and append it again.
I have to execute the program many times for my testing and i don't want to append the same text again and again....
Could you please help me to solve this problem..
this might work
Text text;
void callsomefunctionthousendtimes(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File("./myXML.xml")));
text = doc.createTextNode("");
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName("name");
Element fn= (Element) node1.item(0);
//TODO call your functionName(content) 1000 times here
fn.appendChild(text);
printtoXML(doc);
}
void functionName(String content){
text = text.replaceWholeText(text.getWholeText() + content);
}
added bonusus, only load the doc in once
I have a XML in String variable and I want to pass that value into the parse() of DocumentBuilder.
String xml = "<?xml version="1.0 ....>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
But, seems like the last line doesnt work as doc is null.
Is there anything wrong with this? I am just trying take a xml value and convert it to Document.
Thanks for help.
You need something nearer
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
You can trim this to:
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
Note that normally you'd expect an XML File and it'd be:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fullpathtofile));
I have this xml:
InputStream is = new ByteArrayInputStream(
"<data:RobCtiAifoData xmlns:data=\"urn:cz:isvs:rob:schemas:RobDotazyData:v1\" xmlns:reg=\"urn:cz:isvs:reg:schemas:RegTypy:v1\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:cz:isvs:rob:schemas:RobUnivDotazy:v1\"><data:Aifo a=\"b\">1</data:Aifo><data:VyuzitiPoskytnuti>vyuziti</data:VyuzitiPoskytnuti> </data:RobCtiAifoData>"
.getBytes());
// InputStream is = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
Node node = document.getDocumentElement();
when wanna get name of element without namespace so I wanna call substring of name of element withou prefix
node.getNodeName() gives me data:VyuzitiPoskytnuti
and node.getNamespaceURI() or node.getPrefix() gives me just null. So how I can get prefix of node ?
Try enabling namespace support:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
From the JavaDoc for setNamespaceAware:
Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false