Strip empty namesapces from XML using Xquery/Xslt- xmlns=""
Hi,
Can you please tell me what is the xquery/xslt snippet to remove empty namespaces exist in an xml file.
<date xmlns="">20111006</date>
to
<date>20111006</date>
Thanks.
Edited by: user12679330 on 05-Oct-2011 23:32
Edited by: user12679330 on 06-Oct-2011 00:06
here is the xsl snippet, after struggling for more time, did it.. Thanks All
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@* | node()">
<xsl:if test="name()!='date'">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:if>
<xsl:if test="name()='date'">
<date>
<xsl:value-of select="."/>
</date>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Similar Messages
-
Error when reading data from XML using JAXB?
Hi all,
I get the error message when reading data from XML using JAXB.
[org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException
(AbstractUnmarshallerImpl.java:315)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:481)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:168)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
I don't find the reason, please help!
Thanks in advance!The problem is sovled.
-
How to append the declaration tags to generated xml using Xquery
Hi,
How to append the declaration tags to generated xml using Xquery.generated XML is like
<ROOT>
<CHILD1></CHILD1>
<CHILD2></CHILD2>
</ROOT>
Here I want to append the <?xml version="1.0" encoding="ISO-8859-1"?> and the result xml should be
<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
<CHILD1></CHILD1>
<CHILD2></CHILD2>
</ROOT>
Can anybody help to do this.
Thanks
ManiFirst assign this element to a temp variable
<ROOT>
<CHILD1></CHILD1>
<CHILD2></CHILD2>
</ROOT>
Now in XQuery expression create a new variable
<?xml version="1.0" encoding="ISO-8859-1"?>
$temp -
How to remove elements/attributes from XML using Xpath in XSLT ??
Hello ,
Is there anyway or method of Xpath from which I can delete the elements and attributes from XML at runtime ??
Like I have such XML and I have to remove per attribute highlighted below
<person per="and">
<e:emp a="ir" b="ad" >
</e:emp>
</person>
And want a result like this
<person>
<e:emp a="ir" b="ad" >
</e:emp>
</person>
ThanksTo achieve this you can use the bpelx:remove function: http://download.oracle.com/docs/cd/E12483_01/integrate.1013/b28981/manipdoc.htm#CIHJBJFD
your assign will look like:
<bpel:assign>
<bpelx:remove>
<target variable="person" query="/person/@per" />
</bpelx:remove>
</bpel:assign>
Regards,
Melvin -
How to remove empty lines from xml files after removing nodes from document
<pre>
Hi
<b>i have xml document, which is shown below
after removing some nodes from the document ,i am getting empty lines in place of removed nodes,how to resolve this and get the proper xml document without any errors</b>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE Message SYSTEM "TRD01.dtd">
<Message>
<Header>
<CounterPartyType>CLIENT</CounterPartyType>
<CreationTime>20134455</CreationTime>
<ErrorCode>363 </ErrorCode>
<ErrorEnterPriseId>N</ErrorEnterPriseId>
<ErrorStatus>1</ErrorStatus>
<ErrorSystemId>STL</ErrorSystemId>
<ErrorTimes>31</ErrorTimes>
<MessageType>T</MessageType>
<RecipientEnterpriseId>N</RecipientEnterpriseId>
<RecipentSystemId>EXM</RecipentSystemId>
<Remarks>REMARSK</Remarks>
<SenderEnterpriseId>N</SenderEnterpriseId>
<SenderSystemId>TR</SenderSystemId>
</Header>
</Message>
<ErrorCode>363 </ErrorCode>
<ErrorEnterPriseId>NIHK</ErrorEnterPriseId>
<ErrorStatus>1</ErrorStatus>
<ErrorSystemId>STL</ErrorSystemId>
<ErrorTimes>31</ErrorTimes>
XPathExpression expression5 = xpath.compile(xmlpath5);
Object result5 = expression5.evaluate(doc, XPathConstants.NODE);
Node node5 = (Node) result5;
node5.getParentNode().removeChild(node5);
XPathExpression expression6 = xpath.compile(xmlpath6);
Object result6 = expression6.evaluate(doc, XPathConstants.NODE);
Node node6=(Node) result6;
node6.getParentNode().removeChild(node6);
XPathExpression expression7 = xpath.compile(xmlpath7);
Object result7 = expression7.evaluate(doc, XPathConstants.NODE);
Node node7=(Node) result7;
node7.getParentNode().removeChild(node7);
doc.normalize();
doc.normalizeDocument();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.setOutputProperty(OutputKeys.METHOD,"xml");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
the xml output i am getting is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Message>
<Header>
<CounterPartyType>CLIENT</CounterPartyType>
<CreationTime>20134455</CreationTime>
<MessageType>TRD01</MessageType>
<RecipientEnterpriseId>N</RecipientEnterpriseId>
<RecipentSystemId>STL</RecipentSystemId>
<Remarks>REMARSK</Remarks>
<SenderEnterpriseId>N</SenderEnterpriseId>
<SenderSystemId>T</SenderSystemId>
</Header>
</Message>
<b>could you please let me know how to avoid empty lines in the xml doucment output</b>
this is the method i am using to get the result
public void ValidateRecord(String xml){
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
//parse file into DOM
/*DOMParser parser = new DOMParser();
parser.setErrorStream(System.err);
parser.setValidationMode(DTD_validation);
parser.showWarnings(true);*/
System.out.println ("HI THIS xml is validation "+xml);
Resolver res = new Resolver();
db.setEntityResolver(res);
Document doc = db.parse(new InputSource(new StringReader(xml)));
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
// XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");
String xmlpath="/Message/Header/CounterPartyType/text()";
String xmlpath1="/Message/Header/RecipentSystemId/text()";
String xmlpath2="/Message/Header/ErrorSystemId/text()";
XPathExpression expression = xpath.compile(xmlpath);
XPathExpression expression1 = xpath.compile(xmlpath2);
Object result = expression.evaluate(doc, XPathConstants.NODE);
Object result1 = expression1.evaluate(doc, XPathConstants.NODE);
Node node = (Node) result;
Node node1 = (Node) result1;
System.out.println("the values of the string is " +node.getNodeValue());
System.out.println("the values of the string is " +node1.getNodeValue());
// for (int i = 0; i < nodes.getLength(); i++) {
//System.out.println(nodes.item(i).getNodeValue());
// CAHNGING THE RECEIPENT NODE
XPathExpression expression2 = xpath.compile(xmlpath1);
Object result2 = expression2.evaluate(doc, XPathConstants.NODE);
Node node2 = (Node) result2;
System.out.println(node2);
node2.setNodeValue(node1.getNodeValue());
System.out.println(node2);
//removing the nodes from document
String xmlpath3="/Message/Header/ErrorCode";
String xmlpath4="/Message/Header/ErrorEnterPriseId";
String xmlpath5="/Message/Header/ErrorStatus";
String xmlpath6="/Message/Header/ErrorSystemId";
String xmlpath7="/Message/Header/ErrorTimes";
XPathExpression expression3 = xpath.compile(xmlpath3);
Object result3 = expression3.evaluate(doc, XPathConstants.NODE);
Node node3 = (Node) result3;
node3.getParentNode().removeChild(node3);
XPathExpression expression4 = xpath.compile(xmlpath4);
Object result4 = expression4.evaluate(doc, XPathConstants.NODE);
Node node4 = (Node) result4;
System.out.println("node value");
System.out.println(node4.getParentNode().getNodeName());
node4.getParentNode().removeChild(node4);
XPathExpression expression5 = xpath.compile(xmlpath5);
Object result5 = expression5.evaluate(doc, XPathConstants.NODE);
Node node5 = (Node) result5;
node5.getParentNode().removeChild(node5);
XPathExpression expression6 = xpath.compile(xmlpath6);
Object result6 = expression6.evaluate(doc, XPathConstants.NODE);
Node node6=(Node) result6;
node6.getParentNode().removeChild(node6);
XPathExpression expression7 = xpath.compile(xmlpath7);
Object result7 = expression7.evaluate(doc, XPathConstants.NODE);
Node node7=(Node) result7;
node7.getParentNode().removeChild(node7);
// Node b13Node = (Node) expression.evaluate(doc, XPathConstants.NODE);
//b13Node.getParentNode().removeChild(b13Node);
doc.normalize();
doc.normalizeDocument();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.setOutputProperty(OutputKeys.METHOD,"xml");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.transform(new DOMSource(doc), new StreamResult(System.out));
catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
</pre>
Edited by: user12185243 on Apr 6, 2013 6:38 AM
Edited by: user12185243 on Apr 6, 2013 6:41 AM
Edited by: user12185243 on Apr 6, 2013 6:43 AM
Edited by: user12185243 on Apr 6, 2013 6:45 AM
Edited by: user12185243 on Apr 6, 2013 9:00 AMeither this way we can do this
1)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
<b> factory.setIgnoringElementContentWhitespace(true); </b>
DocumentBuilder db = factory.newDocumentBuilder();
or
2)
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
t.transform(new DOMSource(doc), sr);
String xml1 = sw.toString().trim();
<b> xml1=xml1.replaceAll("\\s",""); </b>
System.out.println(xml1.trim()); -
Remove element from xml using dom.
i want to remove an element from an xml file using dom.
i remove the element but the whole content of the file is also deleted.
how can i rewrite the file.vij_ay wrote:
subject :Remove element from xml,but if empty element in input file then output should be <tag></tag>, not like <tag.xml/>I assume you mean <tag/> but why do you want this? Any application that will not accept this valid XML construct is flawed and a bug report should be raised against it. -
How to remove empty tags from XML
Hello,
I have a XML file which contains some empty tags and some values with "?". I need to remove all empty tags and tags which have a value "?".
Sample Data:
<a>
<b></b>
<c> Hello </c>
<d>world ?</d>
<e>oracle</e>
</a>
Expected result:
<a>
<c> Hello </c>
<e>oracle</e>
</a>
Thank you for your time.
Thanks,
Edited by: 850749 on Apr 7, 2011 6:25 PMDear Odie,
May I make your example a bit more complicated by adding an additional complexType, please:
---Original ----
<DEPT>
<EMPID>1</EMPID>
<EMPNAME>Martin Chadderton</EMPNAME>
<SALARY>??</SALARY>
<SALARYq></SALARYq>
</DEPT>
----- New ----
<DEPT>
<EMPID>1</EMPID>
<EMPNAME>Martin Chadderton</EMPNAME>
<SALARY>??</SALARY>
<SALARYq></SALARYq>
<EMPLMNT_HISTORY>
<DEVISION>1</DEVISION>
<FROM_DATE>2011-01-01 </FROM_DATE>
<TO_DATE></TO_DATE>
</EMPLMNT_HISTORY>
</DEPT>
Your solution works perfectly for <SALARY>, but how would you suggest also to deal with <TO_DATE> ?
Massive thanks for your help!
N.B. Just to emphasise, in my case I have 3 levels (complexType > complexType > complexType) and many elements and I would like to know if there is any generic option to say
to remove all the empty elements from the result, as it causes to the SSJ (Systinet) Webservice to crash. -
How to read xml-stylesheet Processing Instruction from XML using DOM Parser
Hi,
I am trying to read an xml that contains xsl stylesheet PI using DOMParser. The parse() method reads the entire contents of the XML except the PI instruction. Below is the XML I am using to read
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="../../../lang/en-us/style0/usc_profile.xsl" type="text/xsl"?>
<Oblix oblang="en-us" xmlns="http://www.oblix.com/" xmlns:oblix="http://www.oblix.com/">
<ObProfile>
</ObProfile>
</Oblix>
Can anyone let me know if there are any propery settings to be done for the DOM parser before parsing?. If so, what is the property to be set?.
Thanks in Advance
MuthuA COTS product builds the XML and inserts the respective xsl (xml:stylesheet) file name to be used for transforming the xml. I am trying to interrupt this xml and make some updations on an element and finally send the updated xml to the stream.
For the above process, I parse the input XML using DOMParser and update the elements (some internal elements). While I view the final XML that would be passed to the stream, I found the <?xml-stylesheet... PI is missing.
I somehow managed using a temp fix by doing the below. I manually pulled the PI using document.getFirstChild().getNodeValue() and reconstructed the PI and inserted it to the outgoing XML. This needs to be done every time. This might run into problems when more than one PI is used in the XML.
If the parsed XML could get the PI along with it the above problem could be resolved.
Is there any property that could be set on the parser (prior to parsing) to resolve the issue?. -
Counting number of lines in a text/csv file using xquery/xslt.
Hi,
I have a CSV file, I need to count the total number of lines in that file. This I have to use in OSB. My requirement is I have to count total no of lines in the $body file (CSV/flat file) and subtract header and footer lines from it.
EX:
header,1, @total_no_of_detal@
detail,1
detail,2
detail,3
detail,n
footer, 1
If suppose i have 10 detail lines, and I am getting body of the file as shown above,
then in the final file, I have to change the body of the file as:
header,1, *10*
detail,1
detail,2
detail,3
detail,n
footer, 1
Please advice how to do this in OSB.
Edited by: user12679330 on Aug 2, 2011 2:34 AMI would suggest you to use MFL to convert the file into XML when you read it and then you can count the detail elements within the XML and update the values in Header element before writing the file again in flat file format again using MFL.
You can read the documentation of Format Builder utility which is used to define MFL here:
http://download.oracle.com/docs/cd/E21764_01/doc.1111/e15866/part_fb.htm
Alternatively, another approach is the read the whole flat file as a text string and then doing needed manipulations to get what you need. If you want to do it like this then you will need to consider following things:
1. Is the file in DOS format or Unix format? (To know the End of line character in use)
2. Does the file contain an end of line at the end of file? (whether there is an end of line char at the end of data of footer record)
Once you know above, you can try an xquery like following:
let $intermediateXML :=
<Root>
for $a in (tokenize($in, 'EOL'))
return
if (string-length($a) > 0)
then
<record>{$a}</record>
else ()
</Root>
let $count := count($intermediateXML/record)
let $outXML :=
<OutRoot>
for $i in 1 to $count
return
if (data($i) = 1)
then
<Record>{concat($out, $intermediateXML/record[$i]/text(), ',Count=',($count)-2)}</Record>
else
<Record>{concat($out, $intermediateXML/record[$i]/text())}</Record>
</OutRoot>
return op:concatenate($outXML/Record/text(), 'EOL')In Above XQuery, replace EOL with the end of line character which for unix wound be "
 ;" (remove quotes and space between the A and ; ) and for DOS would be "
 ;
 ;" (remove quotes and space between the A and ; and D ; ) -
How to remove xmlns from xml using java
Hi,
<DLList xmlns="http://www.test.com/integration/feed" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Bagalkote</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Devengiri</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
</DLList>
The above xml needs to be decomposed using xsu.I am facing a small problem because the xml has namespaces.
How to remove the namespace using java to get the below xml
Note:I am using XSLT for the transformation.The XSLT tag is not identifying the <DLList> tag with name space
<DLList>
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Bagalkote</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Devengiri</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
</DLList>
Please help.Let me know if any other information is required
ThanksOK, here goes :
For the example, I'll use a TB_DISTRICT table with the following structure :
create table tb_district (
sr_no number(3),
district_name varchar2(100)
);loaded with data from this page :
http://india.gov.in/knowindia/districts/andhra1.php?stateid=KA
and this XML document (one additional record compared to the one you posted) :
<DLList xmlns="http://www.test.com/integration/feed" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Bagalkote</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Devengiri</ForecastName>
<Humidity>89.9</Humidity>
</Weather>
<Weather>
<StateName>Karnataka</StateName>
<ForecastName>Dharwad</ForecastName>
<Humidity>70.1</Humidity>
</Weather>
</DLList>In order to access the XML, I'll also use this Oracle directory object :
create directory test_dir as 'D:\ORACLE\test';Final relational tables are :
create table BUSINESS_TABLE
STATE VARCHAR2(30),
DISTRICT_NAME VARCHAR2(30),
HUMIDITY NUMBER
);and
create table REJECT_TABLE
STATE VARCHAR2(30),
DISTRICT_NAME VARCHAR2(30),
HUMIDITY NUMBER,
ERROR_MESSAGE VARCHAR2(500)
);With XMLTable function, we can easily break the XML into relational rows and columns ready to use for DML :
SQL> alter session set nls_numeric_characters=". ";
Session altered
SQL>
SQL> SELECT *
2 FROM XMLTable(
3 XMLNamespaces(default 'http://www.test.com/integration/feed'),
4 '/DLList/Weather'
5 passing xmltype(bfilename('TEST_DIR','test.xml'), nls_charset_id('CHAR_CS'))
6 columns
7 state varchar2(30) path 'StateName'
8 , district_name varchar2(30) path 'ForecastName'
9 , humidity number path 'Humidity'
10 )
11 ;
STATE DISTRICT_NAME HUMIDITY
Karnataka Bagalkote 89.9
Karnataka Devengiri 89.9
Karnataka Dharwad 70.1
Then with a multitable insert, we load both the business table and the reject table (if the district name does not exist in TB_DISTRICT) :
SQL> INSERT FIRST
2 WHEN master_district_name IS NOT NULL
3 THEN INTO business_table (state, district_name, humidity)
4 VALUES (state, district_name, humidity)
5 ELSE INTO reject_table (state, district_name, humidity, error_message)
6 VALUES (state, district_name, humidity, 'Invalid district name')
7 WITH xml_data AS (
8 SELECT *
9 FROM XMLTable(
10 XMLNamespaces(default 'http://www.test.com/integration/feed'),
11 '/DLList/Weather'
12 passing xmltype(bfilename('TEST_DIR','test.xml'), nls_charset_id('CHAR_CS'))
13 columns
14 state varchar2(30) path 'StateName'
15 , district_name varchar2(30) path 'ForecastName'
16 , humidity number path 'Humidity'
17 )
18 )
19 SELECT x.*
20 , t.district_name as master_district_name
21 FROM xml_data x
22 LEFT OUTER JOIN tb_district t ON t.district_name = x.district_name
23 ;
3 rows inserted
SQL> select * from business_table;
STATE DISTRICT_NAME HUMIDITY
Karnataka Dharwad 70.1
SQL> select * from reject_table;
STATE DISTRICT_NAME HUMIDITY ERROR_MESSAGE
Karnataka Bagalkote 89.9 Invalid district name
Karnataka Devengiri 89.9 Invalid district name -
How to retrieve information from XML using servlets
Hi
I have a scenario like this
File-->XI-->J2ee application(HTTP Receiver adapter)
I want to know how XI sends xml file as a query string file name?
What ever may be the case i just need to retrieve the information from Request object and display the same in browser(JSP).How to do that, I am totally confused, please anyone help me!
Code help is highly rewarded.
ThanxHi Rajesh!
I have tried your code. But some where i went wrong. Please correct me: I am using NWDS2.0.9
my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>WEB APP</display-name>
<description>WEB APP description</description>
<servlet>
<servlet-name>DisplayRes</servlet-name>
<servlet-class>com.quinnox.DisplayRes</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayRes</servlet-name>
<url-pattern>/DisplayRes/*</url-pattern>
</servlet-mapping>
</web-app>
my application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name>ReceiverEntpr</display-name>
<description>EAR description</description>
<module>
<web>
<web-uri>HttpReceiver.war</web-uri>
<context-root>/HttpReceiver</context-root>
</web>
</module>
</application>
and my servlet code:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import com.sun.java_cup.internal.parser;
import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
public class DisplayRes extends HttpServlet {
public void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException
doWork(requset, response);
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
doWork(req, resp);
private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException
String path = null;
PrintWriter out = null;
PrintWriter p2=resp.getWriter();
try
resp.setContentType("text/xml");
out = resp.getWriter();
out.println("hi");
path = req.getPathInfo();
if(req.getContentLength() != -1){
outputURI(req.getInputStream(), out);
} catch (IOException ioe) { return;
//private void outputURI(InputStream resultStream, Writer out) {
private void outputURI(InputStream resultStream, PrintWriter out) {
if (resultStream == null) {
// no default file
// logger.error("No File to return");
return;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Class clazz = loader.loadClass("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
// DocumentBuilderFactoryImpl factory = (DocumentBuilderFactoryImpl) clazz.newInstance();
// DocumentBuilder parser = factory.newDocumentBuilder();
parser.setEntityResolver(new ClassPathEntityResolver());
printXML(parser.parse(resultStream), out);
resultStream.close();
} catch (Exception e) {
// logger.error("Trying to parse the output " , e);
//private void printXML(Document document, Writer writer) throws Exception {
private void printXML(Document document, PrintWriter writer) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source = new DOMSource(document);
Result output = new StreamResult(System.out);
transformer.transform(source, output);
// Write as XML so that entity references can be resolved.
if (writer != null) {
transformer.transform(source, new StreamResult(writer));
Please tell me how to display in servlet.
If it is better to display in a browser. Please send me the code.
Thanks -
Import data from xml using ssis
Using Sql Server 2012 STD edition, SSDT (Visual Studio 2010 shell, .net framework 4.0.3 SP1
I am trying to import data from an xml file using ssis.
Here are the three options I tried and none worked. Please see errors that I encountered in all options and let me know what I can do to import this data in sql
server.
I created a new ssis project with an ssis package. I pulled a data flow task on the control flow. On the data flow tab I pulled an xml source and a sql server
destination. Now I tried to configure the xml source task in the the following three ways, but none worked.
1. I browse the xml file to set xml location. Browse the xsd file to set xsd location, then click ok. I get the following error:
HRESULT errorcode 0xC02090CF from a method call. There was an error setting up the mapping. Undefined complex Type 'gml_V4.1_Release:PolygonType'
is used as a base for complex type extension
2. I browse the xml file to set xml location. check "Use inline schema" Click ok. Error:
HRESULT errorcode 0xC020929E from a method call. The xml source adapter was unable to process the XML data. Multiple inline schemas are not supported.
3.I browse the xml file to set xml location. Click "Generate XSD". Error: The supplied xml instance is a schema or contains inline schema. The
class cannot infer a schema for a schema.
Thank you for your help.Hi ,
I think something problem with the XSD file i too faced somewhat same problem, i have created XSD file from the following link and tried in my package it has worked why don't u try to create xsd file from following link and try again once.
http://xmlgrid.net/xml2xsd.html
Niraj Sevalkar -
Remove tags from XML using transformation
Can anybody tell me how to remove empty tags using xsl transformation.
<App_Data App="MOD" Name="Metadata_Id" Value="SP1282"/>
<App_Data App="MOD" Name="Metadata_Spec_Major_Version" Value=""/>
<App_Data App="MOD" Name="Metadata_Spec_Minor_Version" Value=""/>
My XML will have tags similar to above. My requirement is to remove all tags having attribute Value="". How can i achieve this using transformation.
Thanks
KrishYou need to add the xsi:nil="true" attribute to your xsl-construct to be able to ommit the xml-element which are empty.
To be able to do this you need to add a choose-when-otherwise xsl construct inside your mapping file to test for ""-values.
The xsi:nill='true' isn't supported in the transform-activity yet, you need to add this attribute manually inside your xsl-mapping file.
Kind regards,
Nathalie -
Problem inserting into DB from XML using XSQL
Hi everyone!
I try to load an XML document into a DB table, for the moment i only get access to a MySQL DB server, but i hope to use ORACLE soon. My problem is the next one:
when i try to execute an insert query against the DB server it always fails, i get no problem doing another operation like select and so on. I have try in several ways:
1. From a XSQL page using the tags xsql:insert-request, in the case the error looks like:
Action xsql:insert-request
Message org.gjt.mm.mysql.jdbc2.Connection
2. I also have try the MoreoverIntoNews java examples, and the problem seem similar:
Exception in thread "main" oracle.xml.sql.OracleXMLSQLException:
org.gjt.mm.mysql.jdbc2.Connection
at oracle.xml.sql.dml.OracleXMLSave.saveXML(OracleXMLSave.java:1967)
at oracle.xml.sql.dml.OracleXMLSave.insertXML(OracleXMLSave.java:1060)
at MoreoverIntoNewsstory.main(MoreoverIntoNewsstory.java:43)
How can i fix this problem?
I also have realize that when i remove from the CLASSPATH the file "classes12.zip" then i
get next exception:
java.lang.NoClassDefFoundError: oracle/sql/CLOB
Then it seems that the XML-SQL utilities (XSU) are only to work with Oracle and not with other DB engine.
Thanks in advance.
Marcos.Is there a solution to this problem? Does anyone have any suggestions?
-
Extracting data from XML using xmltype and extract
Hello all,
I want to write a pl/sql functions that takes a clob as an input and return a some data extracted from the data passed into it.
the input will be an xml similar to the following:
<FIXML xsi:schemaLocation="http://www.finacle.com/fixml executeFinacleScript.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
<ResponseHeader>
<RequestMessageKey>
<RequestUUID>IVR201306180841060310000000000000000</RequestUUID>
<ServiceRequestId>executeFinacleScript</ServiceRequestId>
<ServiceRequestVersion>10.3</ServiceRequestVersion>
<ChannelId>IVR</ChannelId>
</RequestMessageKey>
<ResponseMessageInfo>
<BankId>01</BankId>
<TimeZone></TimeZone>
<MessageDateTime>2013-06-18T05:36:55.918</MessageDateTime>
</ResponseMessageInfo>
<UBUSTransaction>
<Id/>
<Status/>
</UBUSTransaction>
<HostTransaction>
<Id/>
<Status>SUCCESS</Status>
</HostTransaction>
<HostParentTransaction>
<Id/>
<Status/>
</HostParentTransaction>
<CustomInfo/>
</ResponseHeader>
</Header>
<Body>
<executeFinacleScriptResponse>
<ExecuteFinacleScriptOutputVO>
<executeFinacleScript_customData>
<DataCategory>ACC</DataCategory>
<New_Data>0001019300101001</New_Data>
</executeFinacleScript_customData>
</ExecuteFinacleScriptOutputVO>
</executeFinacleScriptResponse>
</Body>
</FIXML>'
I want to extract the value of new_data.
I wrote the following anonymous block to test the code :
declare
xparam xmltype;
v_xpath varchar2(500);
begin
xparam:=xmltype('<FIXML xsi:schemaLocation="http://www.finacle.com/fixml executeFinacleScript.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
<ResponseHeader>
<RequestMessageKey>
<RequestUUID>IVR201306180841060310000000000000000</RequestUUID>
<ServiceRequestId>executeFinacleScript</ServiceRequestId>
<ServiceRequestVersion>10.3</ServiceRequestVersion>
<ChannelId>IVR</ChannelId>
</RequestMessageKey>
<ResponseMessageInfo>
<BankId>01</BankId>
<TimeZone></TimeZone>
<MessageDateTime>2013-06-18T05:36:55.918</MessageDateTime>
</ResponseMessageInfo>
<UBUSTransaction>
<Id/>
<Status/>
</UBUSTransaction>
<HostTransaction>
<Id/>
<Status>SUCCESS</Status>
</HostTransaction>
<HostParentTransaction>
<Id/>
<Status/>
</HostParentTransaction>
<CustomInfo/>
</ResponseHeader>
</Header>
<Body>
<executeFinacleScriptResponse>
<ExecuteFinacleScriptOutputVO>
<executeFinacleScript_customData>
<DataCategory>ACC</DataCategory>
<New_Data>0001019300101001</New_Data>
</executeFinacleScript_customData>
</ExecuteFinacleScriptOutputVO>
</executeFinacleScriptResponse>
</Body>
</FIXML>');
v_xpath:='//New_Data/text()';-
dbms_output.put_line(xparam.EXTRACT(v_xpath).GETSTRINGVAL());
end;
but I get the following Error:
dbms_output.put_line(xparam.EXTRACT(v_xpath).GETSTRINGVAL());
end;
Error at line 1
ORA-30625: method dispatch on NULL SELF argument is disallowed
ORA-06512: at line 46
the problem is that when I remove : xmlns="http://www.finacle.com/fixml" attribute from the root node the code works correctly.
of course , I can simply use replace to remove it, but I want to know what is causing the error.
I am using oracle database 10gLet me explain that the issue is not only related to Oracle.
If you google a bit for default namespace and Xpath you will find many topic.
Basically when you have an XML having a definition of namespace without a prefix:
i.e.:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example XHTML document</title>
</head>
<body>
<p>Sample content</p>
</body>
</html>
this means that all unprefixed elements are belonging to this default namespace.
In this case an Xpath equal to '//title/text()' will not get anything because it is assuming to find the element title within a null namespace. But title in this case is automatically assigned to the default namespace.
When you specify a prefix in a namespace then all elements without prefix are associated to namespace NULL. Using a default namespace is causing a lot of headache.
These links can be giving a clearer picture:
http://www.edankert.com/defaultnamespaces.html
Assuming that you have data like this:
WITH mydata AS
( SELECT '
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example XHTML document</title>
</head>
<body>
<p>Sample content</p>
</body>
</html>' xmldata FROM DUAL
SELECT xmltype (xmldata).EXTRACT ('//title/text()').getstringval ()
FROM mydata;
This query will not give anything back to you. You will have to specify:
SELECT xmltype (xmldata).EXTRACT ('//title/text()', 'xmlns="http://www.w3.org/1999/xhtml"').getstringval ()
FROM mydata;
Note also that you should be able to get the default namespace when it is specified (without prefix) by using:
SELECT xmltype(xmldata).getnamespace() from mydata;
Post your Oracle version to see if it something related to your version. In mine I got this:
SQL*Plus: Release 11.2.0.1.0 Production on Thu Jun 20 18:32:58 2013
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> WITH mydata AS
2 ( SELECT '
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>Example XHTML document</title>
6 </head>
7 <body>
8 <p>Sample content</p>
9 </body>
10 </html>' xmldata FROM DUAL
11 )
12 SELECT xmltype(xmldata).getnamespace() from mydata;
XMLTYPE(XMLDATA).GETNAMESPACE()
http://www.w3.org/1999/xhtml
SQL>
If this would work, then it would be enough to add the optional additional parameter namespace. In case it is null it will be set as xmlsn="" and it will work anyway:
Please note that it will work both if the XML has a default namespace or not
i.e.:
with default namespace:
SQL> DECLARE
2 xparam XMLTYPE;
3 v_xpath VARCHAR2 (500);
4 v_ns VARCHAR2 (500);
5 BEGIN
6 xparam :=
7 xmltype ('
8 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ns="http://www.w3.org/1999/xhtml" >
9 <head>
10 <title>Example XHTML document</title>
11 </head>
12 <body>
13 <p>Sample content</p>
14 </body>
15 </html>');
16 v_xpath := '//title/text()';
17 v_ns := 'xmlns="' || xparam.getnamespace () || '"';
18 DBMS_OUTPUT.
19 put_line (
20 'Value of title:' || xparam.EXTRACT (v_xpath, v_ns).getstringval ());
21 END;
22 /
Value of title:Example XHTML document
PL/SQL procedure successfully completed.
SQL>
and without default namespace
SQL> DECLARE
2 xparam XMLTYPE;
3 v_xpath VARCHAR2 (500);
4 v_ns VARCHAR2 (500);
5 BEGIN
6 xparam :=
7 xmltype ('
8 <html xmlns:ns="http://www.w3.org/1999/xhtml" >
9 <head>
10 <title>Example XHTML document</title>
11 </head>
12 <body>
13 <p>Sample content</p>
14 </body>
15 </html>');
16 v_xpath := '//title/text()';
17 v_ns := 'xmlns="' || xparam.getnamespace () || '"';
18 DBMS_OUTPUT.
19 put_line (
20 'Value of title:' || xparam.EXTRACT (v_xpath, v_ns).getstringval ());
21 END;
22 /
Value of title:Example XHTML document
PL/SQL procedure successfully completed.
Regards.
Al
Message was edited by: AlbertoFaenza
IF removed as it is working anyway.
Maybe you are looking for
-
Delivery has failed to these recipients or distribution lists: [email protected] Your message wasn't delivered because of security policies. Microsoft Exchange will not try to redeliver this message for you. Please provide the following diagnostic te
-
How to have multiple default dimension members
Hi There I am using AS2008, when editing a role, under the dimension data tab, under advanced, you can define a default dimension member. However i need my default dimension member to be members, i have tried using a attribute set to true for many me
-
Re Downloading apps help please
Hi, I have a nokia 5530 XM. I t had a few troubles at the beginning so i had to format the memory card and it's fine now. But i've lost all my apps and i go to the store to re download them but the download button is darker and it wont let me re down
-
Downloading an app, prompts me I can't download 23 apps
When I download an app from the app store, after I give my apple id password, it will tell me 23 apps cannot be downloaded at this time (including whatsapp and some others..) I don't need to download these apps and there is no update for whatsapp.. s
-
HT5022 Airport Utility 5.6 would not install
Airport Utility 5.6 would not install on my MacBook Pro with 10.7.5 (Lion): "The installer encountered an error that caused the installation to fail. Contact the software manufacturer for assistance." Hello, Apple?