Adding namespace definition to xml using apache xmlbeans - java

I need to add namespace defintion to an element since its not getting added when when xml is generated using apache xmlbean. How do I acheieve this using xmlbeans API?

I have found answer to the problem.
Here's how it is.
XmlCursor cursor= targetObject.newCursor();
cursor.toNextToken();
cursor.insertNamespace("A", "namespace1");
//For example
cursor.insertNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
cursor.dispose();

Use:
XmlOptions.setSaveSuggestedPrefixes()
XmlOptions xmlOptions = new XmlOptions();
xmlOptions.setSavePrettyPrint();
xmlOptions.setSavePrettyPrintIndent(4);
xmlOptions.setSaveAggressiveNamespaces();
HashMap<String, String> nsMap = new HashMap<String, String>();
nsMap.put("namespace1","A");
nsMap.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");
xmlOptions.setSaveSuggestedPrefixes(nsMap);
// Create your XmlObject
<Your XmlObject>.save(new File("test.xml"),xmlOptions);

Related

How to get Attribute value and tag value using apache configuration libraray

I am using Apache Commons Configuration for reading configuration in xml file.
Ex: Configuration is
<example>
....
<task id="123">example task1</task>
<task id="456">example task2</task>
....
</example>
I want to extract all example.task where I need values in the below form
123-> example task1
456-> example task2
How this can be achieved.
You can use xpath to extract the information you need.
XMLConfiguration config = new XMLConfiguration("ConfigTest.xml");
ConfigurationNode node = config.getRootNode();
config.getString("example/task[id= '123']"); // This returns the exact value
You could also populate a map
Map<String, String> configMap = new HashMap<String, String>();
for (ConfigurationNode c : node.getChildren("task"))
{
String key = (String)c.getAttribute(0).getValue();
String value = (String)c.getValue();
configMap.put(key, value);
}
Code expert from: How to load xml file using apache commons configuration (java)?

how to get null while parsing xml with geotools parser

I tried to get null value from my xml file such below
<top:kadastroParselFeature gml:id="KADASTRO_PARSEL.1">
<top:olcek xsi:nil="true" />
</top:kadastroParselFeature>
but my parser throws such an exception :
java.lang.RuntimeException: Parsing failed for kadastroParselFeature: java.lang.NullPointerException
at org.geotools.xml.impl.ParseExecutor.visit(ParseExecutor.java:164)
at org.geotools.xml.impl.BindingWalker$BindingExecutionChain.execute(BindingWalker.java:220)
at org.geotools.xml.impl.BindingWalker.walk(BindingWalker.java:186)
at org.geotools.xml.impl.ElementHandlerImpl.endElement(ElementHandlerImpl.java:236)
at org.geotools.xml.impl.ParserHandler.endElement(ParserHandler.java:719)
My parser configuration like this :
org.geotools.xml.Configuration configuration = new org.geotools.gml2.GMLConfiguration();
org.geotools.xml.Parser parser = new org.geotools.xml.Parser( configuration );
parser.setFailOnValidationError(false);
HashMap<Object, Object> parsedMap = (HashMap<Object, Object>) parser.parse( isx);
if I remove xsi:nill="true" from element it returns ""(empty string) but i need null .
there is a usage of my parser at http://docs.geotools.org/stable/userguide/library/xml/geometry.html
I found a solution for my work the problem at my gml writer version if i changed the version from gml2 to gml3 the problem not seen. and ı changed my parser config. like this
org.geotools.xml.Configuration configuration = new org.geotools.gml3.ApplicationSchemaConfiguration("sampleURL", "sample.xsd");
org.geotools.xml.Parser parser = new org.geotools.xml.Parser( configuration );

How to create a typical XML Header with XML Beans in Java?

I would like to create a specific xml document with XML Beans. So I have been reached an acceptable result like this one:
<Req accessId="1234" ver="1.1">
<Loc id="007" maxNr="5">
<Altitude x="123" y="987" type="ABC"/>
</Loc>
</Req>
Now a need the XML Documents´s typical XML Header, but I not found a solution by using XMLBeans. This is that I need as result:
<?xml version="1.0" encoding="UTF-8"?>
<Req accessId="1234" ver="1.1">
<Loc id="007" maxNr="5">
<Altitude x="123" y="987" type="ABC"/>
</Loc>
</Req>
The Java Code, which create the XMl Result on console:
XmlOptions options = new XmlOptions();
Map<String, String> substNameSpaces = new HashMap<String, String>();
substNameSpaces.put("ext", null);
options.setSavePrettyPrint();
options.setLoadSubstituteNamespaces(substNameSpaces);
options.setUseDefaultNamespace();
options.setSaveOuter();
// ReqDocument
ReqDocument doc = ReqDocument.Factory.newInstance(options);
// Req
Req req = doc.addNewReq();
req.setAccessId("1234");
req.setVer("1.1");
// Loc
Loc locValReq = req.addNewLoc();
loc.setId("007");
loc.setMaxNr(5);
// Altitude
Location location = loc.addNewAltitude();
location.setX(123);
location.setY(987);
location.setType("ABC");
// Outline
System.out.println(req.xmlText(options));
Can anybody help me?

Parsing XML node's attribute with prefixes - XSTREAM/JAVA

I'm using StaxDriver with XStream and trying to parse this XML:
<cad:MyObj xmlns:cad="namespace" cad:testeId="873" >
<cad:node1>value node 1</cad:node1>
</cad:MyObj>
into an object.
I can parse node1 with the prefix but I don't know how to configure XStream with Stax to use the prefix cad with atributes (testeId).
Here's my conf:
QNameMap qnameMap = new QNameMap();
qnameMap.setDefaultPrefix("cad");
qnameMap.setDefaultNamespace("namespace");
StaxDriver stax = new StaxDriver(qnameMap);
stax.getInputFactory().setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
stax.setRepairingNamespace(true);
stax.setQnameMap(qnameMap);
xstream = new XStream(stax);
xstream.alias("MyObj", MyObj.class);
xstream.useAttributeFor(MyObj.class, "testeId");
I've tried to "cheat" with this:
xstream.aliasField("cad:testeId", ProdutoVersao.class, "testeId");
but didn't work =/
Hope someone know how to do it.
Well. I think there is no solution for this using XStream.
I've changed to JAXB with a namespace prefix mapper:
http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
Marshaller m = context.createMarshaller();
ProdutoVersaoPrefixMapper mapper = new ProdutoVersaoPrefixMapper();
m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", mapper);
With this code the node and his attributes get the prefix.

(de)serialize an object(Hashmap) from an XML of this form with XStream

XML:
JAVA Hashmap:
map = {key1=text1,key2=text2}
this doesn't work. why?
String xml = "<nodes><node id=\"key1\"><![CDATA[text1]]></node><node id="\key2\"><![CDATA[text2]]></node></nodes>";
XStream xs = new XStream();
xs.alias("nodes", Map.class);
xs.alias("node", String.class);
xs.useAttributeFor("id",String.class);
Map<String,String> map= (Map<String,String>) xs.fromXML(xml);
System.out.println(map);
If you can define your XML structure you should check the Map Converter and adjust your XML.
If not, you should write your own custom converter. You can see this thread to check an implementation similar to your needs.

Categories