Parse XML document with LINQ TO XML
Hello,
I need to parse an XML Feed that looks like this:
<ContentAPI xmlns="http://www.geneity.co.uk/genbet/ContentAPI" status="OK" timezone="UTC" msg_stamp="NzMzNzUzNzE6MTAyMTppdA==" version="1.0" request="get_sports">
<Sport sport_code="FOOT" name="Calcio" has_events="Y" disporder="-2"/>
<Sport sport_code="TENN" name="Tennis" has_events="Y" disporder="1"/>
<Sport sport_code="BASK" name="Basket" has_events="Y" disporder="2"/>
<Sport sport_code="VOLL" name="Pallavolo" has_events="Y" disporder="4"/>
<Sport sport_code="HAND" name="Pallamano" has_events="N" disporder="5"/>
<Sport sport_code="ICEH" name="Hockey su Ghiaccio" has_events="Y" disporder="6"/>
<Sport sport_code="AMFO" name="Football Americano" has_events="N" disporder="7"/>
<Sport sport_code="BASE" name="Baseball" has_events="Y" disporder="7"/>
</ContentAPI>
I want to use LINQ TO XML in order to read it into an object var.
This is the code that i wrote but i doesn't work...
XDocument xdoc = XDocument.Load(string.Format("myURL....."));
var Sport = from feed in xdoc.Descendants("Sport")
select new
_sport_code = feed.Attribute("sport_code").Value,
_name = feed.Attribute("name").Value,
_has_events = feed.Attribute("has_events").Value,
_disporder = feed.Attribute("disporder").Value
foreach (var s in Sport)
The program doesn't run inside the foreach loop...
for sure the problem is on the linq to xml query...
Thanks for your help
Hello, I'm back again...
Now I have to parse a second file XML with some little differences on the track:
<ContentAPI xmlns="http://www.geneity.co.uk/genbet/ContentAPI" status="OK" timezone="UTC" msg_stamp="NzM1NTQ5MDQ6MTAyMTppdA==" version="1.0" request="get_classes_for_sport">
<Sport sport_code="FOOT" name="Calcio" disporder="-2">
<SBClass sb_class_id="12432" name="Italia" has_events="Y" disporder="-9999"/>
<SBClass sb_class_id="14603" name="Euro 2016" has_events="N" disporder="-1000"/>
</Sport>
</ContentAPI>
The C# code to get the SBClass elements is this:
XDocument xdoc = XDocument.Load(string.Format(url_Get_Region_By_Lang_Sport, pCodLang, pCodSport));
var SportRegion = from _SportRegion in xdoc.Descendants(XName.Get("Sport", "http://www.geneity.co.uk/genbet/ContentAPI")).Descendants("SBClass")
select new
CodSport = _SportRegion.Attribute("sport_code").Value.Trim(),
SbRegionId = _SportRegion.Attribute("name").Value.Trim(),
Region = _SportRegion.Attribute("has_events").Value.Trim(),
HasEvents = _SportRegion.Attribute("disporder").Value.Trim(),
RegionOrder = _SportRegion.Attribute("disporder").Value.Trim()
foreach(var sptr in SportRegion)
The program doesn't step inside the foreach loop...
Thanks again!
Similar Messages
-
Parsing xml using DOM parser in java
hi there!!!
i don have much idea about parsing xml.. i have an xml file which consists of details regarding indentation and spacing standards of C lang.. i need to read the file using DOM parser in java n store each of the attributes n elements in some data structure in java..
need help as soon as possible!!!DOM is the easiest way to parse XML document, google for JDOM example it is very easy to implement.
you need to know what is attribute, what is text content and what is Value in XML then easily you can parse your document with dom (watch for space[text#] in your XML document when you parse it).
you get root node then nodelist of childs for root then go further inside, it is easy believe me. -
Flash CS5 error: Flash can not parse this document
The amount of times Flash CS has crashed on me and ive lost documents is unbelievable now. Yesterday i closed down Flash CS5 normally (no crash or anything) and today i load my file back up and it says in the output "Flash can not parse this document" with an error saying an error occurred opening file bla bla. I had a backup of the file too ALSO that does not work with the same problem. The last time this happened to me i was told it was because i had a document on the network so ive been working locally on my drive ever since and this problem arises again.
The project i was working on was important and i want a solution to this problem please.Hi guswebb,
We are currently looking into these issues. Can you please send the file with the bad UIScrollBar.xml to me at [email protected]? Please zip your file and change .zip extension to .zzz before attaching to email.
Thanks,
Quynh
Flash Pro, QE -
Create document with PL/SQL xml parser
Hello,
I'm trying to create a document with PL/SQL package xmldom on 8.1.7 and write to a file.
The problem is that my file is empty when it's created.
Can anyone send me an example of this simple problem or fullfill my example so it's works.
As you understand I'm new in using XML. :)
My example is:
declare
doc xmldom.DOMDocument;
n xmldom.DOMNode;
e xmldom.domelement;
t xmldom.domtext;
begin
doc := xmldom.newdomdocument;
t := xmldom.createtextnode(doc, 'ROOT');
n := xmldom.makenode(t);
doc := xmldom.makedocument(n);
xmldom.writetofile(doc, 'd:\orant\xdk\plsql\demo\test.xml');
end;
Regards
HekanYour problem may be memory for the JavaVM. Remember, the PL/SQL
parser uses the Java XML Parser APIs which run in a VM instance.
Are you running Oracle 8i? If you are you can access our Java
XML parser loaded in 8i's VM directly from your PL/SQL code.
That is in fact how our PL/SQL Parser does it.
Finally, we have no experience loading other XML Parsers into
Oracle.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
Premal Mehta (guest) wrote:
: Hi,
: I asked about his a few days back. Pl/SQL parser does not
work
: for XML files of size greater then 500Kb. You replied saying
: that there were no such problem.
: However whenever I try, either I get some exception or
Pl/SQL
: crashes due to memory error. I am clueless. Is there some
: setting that I can do to get away with the problem? Please
: guide...
: Also, tell me about the alternatives.
: Can I write code in Java and load these class filesin Oracle
: and then reference these classes from Pl/SQL code. Can I load
: any other parser for Java in Oracle.
: Looking forward for help...
: Premal.
null -
How to parse an XML document with oracle8i
Has anyone a good link or an example how to decode and store an XML document into an oracle8i database.
I' ve found only good things for oracle9i.
Thank you
RogerHere is an example of parsing xml taken fro Oracle8i 8.1.7 xdk.
This one uses external OS files to pase, but could be easily converted to
use CLOB or VARCHAR2 string for parsing XML documents.
IF you wanted to use CLOB to store and manipulate xml documents you can use XMLParser and XMLDom
packages along with the DBMS_LOB package to do that.
-- This file demonstates a simple use of the parser and DOM API.
-- The XML file that is given to the application is parsed and the
-- elements and attributes in the document are printed.
-- The use of setting the parser options is demonstrated.
set serveroutput on;
create or replace procedure domsample(dir varchar2, inpfile varchar2,
errfile varchar2) is
p xmlparser.parser;
doc xmldom.DOMDocument;
-- prints elements in a document
procedure printElements(doc xmldom.DOMDocument) is
nl xmldom.DOMNodeList;
len number;
n xmldom.DOMNode;
begin
-- get all elements
nl := xmldom.getElementsByTagName(doc, '*');
len := xmldom.getLength(nl);
-- loop through elements
for i in 0..len-1 loop
n := xmldom.item(nl, i);
dbms_output.put(xmldom.getNodeName(n) || ' ');
end loop;
dbms_output.put_line('');
end printElements;
-- prints the attributes of each element in a document
procedure printElementAttributes(doc xmldom.DOMDocument) is
nl xmldom.DOMNodeList;
len1 number;
len2 number;
n xmldom.DOMNode;
e xmldom.DOMElement;
nnm xmldom.DOMNamedNodeMap;
attrname varchar2(100);
attrval varchar2(100);
begin
-- get all elements
nl := xmldom.getElementsByTagName(doc, '*');
len1 := xmldom.getLength(nl);
-- loop through elements
for j in 0..len1-1 loop
n := xmldom.item(nl, j);
e := xmldom.makeElement(n);
dbms_output.put_line(xmldom.getTagName(e) || ':');
-- get all attributes of element
nnm := xmldom.getAttributes(n);
if (xmldom.isNull(nnm) = FALSE) then
len2 := xmldom.getLength(nnm);
-- loop through attributes
for i in 0..len2-1 loop
n := xmldom.item(nnm, i);
attrname := xmldom.getNodeName(n);
attrval := xmldom.getNodeValue(n);
dbms_output.put(' ' || attrname || ' = ' || attrval);
end loop;
dbms_output.put_line('');
end if;
end loop;
end printElementAttributes;
begin
-- new parser
p := xmlparser.newParser;
-- set some characteristics
xmlparser.setValidationMode(p, FALSE);
xmlparser.setErrorLog(p, dir || '/' || errfile);
xmlparser.setBaseDir(p, dir);
-- parse input file
xmlparser.parse(p, dir || '/' || inpfile);
-- get document
doc := xmlparser.getDocument(p);
-- Print document elements
dbms_output.put('The elements are: ');
printElements(doc);
-- Print document element attributes
dbms_output.put_line('The attributes of each element are: ');
printElementAttributes(doc);
-- deal with exceptions
exception
when xmldom.INDEX_SIZE_ERR then
raise_application_error(-20120, 'Index Size error');
when xmldom.DOMSTRING_SIZE_ERR then
raise_application_error(-20120, 'String Size error');
when xmldom.HIERARCHY_REQUEST_ERR then
raise_application_error(-20120, 'Hierarchy request error');
when xmldom.WRONG_DOCUMENT_ERR then
raise_application_error(-20120, 'Wrong doc error');
when xmldom.INVALID_CHARACTER_ERR then
raise_application_error(-20120, 'Invalid Char error');
when xmldom.NO_DATA_ALLOWED_ERR then
raise_application_error(-20120, 'Nod data allowed error');
when xmldom.NO_MODIFICATION_ALLOWED_ERR then
raise_application_error(-20120, 'No mod allowed error');
when xmldom.NOT_FOUND_ERR then
raise_application_error(-20120, 'Not found error');
when xmldom.NOT_SUPPORTED_ERR then
raise_application_error(-20120, 'Not supported error');
when xmldom.INUSE_ATTRIBUTE_ERR then
raise_application_error(-20120, 'In use attr error');
end domsample;
show errors; -
Persisting unexplained errors when parsing XML with schema validation
Hi,
I am trying to parse an XML file including XML schema validation. When I validate my .xml and .xsd in NetBeans 5.5 beta, I get not error. When I parse my XML in Java, I systematically get the following errors no matter what I try:
i) Document root element "SQL_STATEMENT_LIST", must match DOCTYPE root "null".
ii) Document is invalid: no grammar found.
The code I use is the following:
try {
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse( new File(PathToXml) );
My XML is:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Defining the SQL_STATEMENT_LIST element -->
<xs:element name="SQL_STATEMENT_LIST" type= "SQL_STATEMENT_ITEM"/>
<xs:complexType name="SQL_STATEMENT_ITEM">
<xs:sequence>
<xs:element name="SQL_SCRIPT" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<!-- Defining simple type ApplicationType with 3 possible values -->
<xs:simpleType name="ApplicationType">
<xs:restriction base="xs:string">
<xs:enumeration value="DawningStreams"/>
<xs:enumeration value="BaseResilience"/>
<xs:enumeration value="BackBone"/>
</xs:restriction>
</xs:simpleType>
<!-- Defining the SQL_SCRIPT element -->
<xs:element name="SQL_SCRIPT" type= "SQL_STATEMENT"/>
<xs:complexType name="SQL_STATEMENT">
<xs:sequence>
<xs:element name="NAME" type="xs:string"/>
<xs:element name="TYPE" type="xs:string"/>
<xs:element name="APPLICATION" type="ApplicationType"/>
<xs:element name="SCRIPT" type="xs:string"/>
<!-- Making sure the following element can occurs any number of times -->
<xs:element name="FOLLOWS" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
and my XML is:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : SQLStatements.xml
Created on : 1 juillet 2006, 15:08
Author : J�r�me Verstrynge
Description:
Purpose of the document follows.
-->
<SQL_STATEMENT_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.dawningstreams.com/XML-Schemas/SQLStatements.xsd">
<SQL_SCRIPT>
<NAME>CREATE_PEERS_TABLE</NAME>
<TYPE>CREATION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
CREATE CACHED TABLE PEERS (
PEER_ID VARCHAR(20) NOT NULL,
PEER_KNOWN_AS VARCHAR(30) DEFAULT ' ' ,
PRIMARY KEY ( PEER_ID )
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>CREATE_COMMUNITIES_TABLE</NAME>
<TYPE>CREATION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
CREATE CACHED TABLE COMMUNITIES (
COMMUNITY_ID VARCHAR(20) NOT NULL,
COMMUNITY_KNOWN_AS VARCHAR(25) DEFAULT ' ',
PRIMARY KEY ( COMMUNITY_ID )
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>CREATE_COMMUNITY_MEMBERS_TABLE</NAME>
<TYPE>CREATION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
CREATE CACHED TABLE COMMUNITY_MEMBERS (
COMMUNITY_ID VARCHAR(20) NOT NULL,
PEER_ID VARCHAR(20) NOT NULL,
PRIMARY KEY ( COMMUNITY_ID, PEER_ID )
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>DROP_PEER_TABLE</NAME>
<TYPE>DELETION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
DROP TABLE PEERS IF EXISTS
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>DROP_COMMUNITIES_TABLE</NAME>
<TYPE>DELETION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
DROP TABLE COMMUNITIES IF EXISTS
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>DROP_COMMUNITY_MEMBERS_TABLE</NAME>
<TYPE>DELETION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
DROP TABLE COMMUNITY_MEMBERS IF EXISTS
</SCRIPT>
</SQL_SCRIPT>
<SQL_SCRIPT>
<NAME>CREATE_COMMUNITY_MEMBERS_VIEW</NAME>
<TYPE>CREATION</TYPE>
<APPLICATION>DawningStreams</APPLICATION>
<SCRIPT>
CREATE VIEW COMMUNITY_MEMBERS_VW AS
SELECT P.PEER_ID, P.PEER_KNOWN_AS, C.COMMUNITY_ID, C.COMMUNITY_KNOWN_AS
FROM PEERS P, COMMUNITIES C, COMMUNITY_MEMBERS CM
WHERE P.PEER_ID = CM.PEER_ID
AND C.COMMUNITY_ID = CM.COMMUNITY_ID
</SCRIPT>
<FOLLOWS>CREATE_PEERS_TABLE</FOLLOWS>
<FOLLOWS>CREATE_COMMUNITIES_TABLE</FOLLOWS>
</SQL_SCRIPT>
</SQL_STATEMENT_LIST>
Any ideas? Thanks !!!
J�r�me VerstryngeHi,
I found the solution in the following post:
Validate xml with DOM - no grammar found
Sep 17, 2003 10:58 AM
The solution is to add a line of code when parsing:
try {
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse( new File(PathToXml) );
The errors are gone !!!
J�r�me Verstrynge -
How to Parse XML with SAX and Retrieving the Information?
Hiya!
I have written this code in one of my classes:
/**Parse XML File**/
SAXParserFactory factory = SAXParserFactory.newInstance();
GameContentHandler gameCH = new GameContentHandler();
try
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(recentFiles[0], gameCH);
catch(javax.xml.parsers.ParserConfigurationException e)
e.printStackTrace();
catch(java.io.IOException e)
e.printStackTrace();
catch(org.xml.sax.SAXException e)
e.printStackTrace();
/**Parse XML File**/
games = gameCH.getGames();And here is the content handler:
import java.util.ArrayList;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
class GameContentHandler extends DefaultHandler
private ArrayList<Game> games = new ArrayList<Game>();
public void startDocument()
System.out.println("Start document.");
public void endDocument()
System.out.println("End document.");
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
public void characters(char[] ch, int start, int length) throws SAXException
/**for (int i = start; i < start+length; i++)
System.out.print(ch);
public ArrayList<Game> getGames()
return games;
}And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<Database>
<Name></Name>
<Description></Description>
<CurrentGameID></CurrentGameID>
<Game>
<gameID></gameID>
<name></name>
<publisher></publisher>
<platform></platform>
<type></type>
<subtype></subtype>
<genre></genre>
<serial></serial>
<prodReg></prodReg>
<expantionFor></expantionFor>
<relYear></relYear>
<expantion></expantion>
<picPath></picPath>
<notes></notes>
<discType></discType>
<owner></owner>
<location></location>
<borrower></borrower>
<numDiscs></numDiscs>
<discSize></discSize>
<locFrom></locFrom>
<locTo></locTo>
<onLoan></onLoan>
<borrowed></borrowed>
<manual></manual>
<update></update>
<mods></mods>
<guide></guide>
<walkthrough></walkthrough>
<cheats></cheats>
<savegame></savegame>
<completed></completed>
</Game>
</Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
Please help someone...OK, how's this?
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
current = "";
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
try
if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
{return;}
else if(qualifiedName.equals("gameID"))
{games.add(new Game(Integer.parseInt(current)));}
else if(qualifiedName.equals("name"))
{games.get(games.size()-1).name = current;}
else if(qualifiedName.equals("publisher"))
{games.get(games.size()-1).publisher = current;}
etc...
else
{System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
catch (Exception e) {} //Ignore
public void characters(char[] ch, int start, int length) throws SAXException
current += new String(ch, start, length);
} -
Getting null value while parsing "XML String" with encoding WINDOWS-1252.
Hi,
when I am converting the Follwoing "xml string " to Document, I am getting the "null" as a document value.
String strXML = "<?xml version="1.0" encoding="WINDOWS-1252"?>
<category name="SearchByAttributes" value="Search By Attributes">
<item name="ORDER_LINE_ID" description="Application Search Attributes" >
<attribute name="Sequence" value="0001"/>
</item>
</category>"
My "xml string" has the encoding vaule: WINDOWS-1252.
I am using the following code to convert the "xml string" to Document. I am getting the Document values as a "null" while converting the above "string xml"
String strXML = //my above string xml.
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new InputSource(new StringReader(strXML)));
System.out.println("doc value.."+doc)//I am getting null value for "doc".
Can anyone help me to resolve the issue.Thagelapally wrote:
I am coverting the below "XML string" to Document, once it is converted I am reading that Document,which have an "attribue" Element in.
String strXML = "<?xml version="1.0" encoding="WINDOWS-1252"?>
<category name="SearchByAttributes" value="Search By Attributes">
<item name="ORDER_LINE_ID" description="Application Search Attributes" >
<attribute name="Sequence" value="0001"/>
</item>
</category>" I am using the above code to read the Document. When run the code in "OC4J Server" and using Jdeveloper as an editor,I am able to perfectly read the "attribute" element in the document with out any problem.Println statement printing as I expected.
System.out.println("Element Name..."+listOfAtt.getNodeName());
//getting Element Name as...."attribute"(as expected)
System.out.println("Element Attibrute list....."+elementAtt);
//getting Element Attribute list as an...."oracle.xml.parser.v2.XMLAttrList@afe"But when run the same code(reading the same Document) in Tomcat and Eclipse,println satatement not printing as i expected.
System.out.println("Element Name..."+listOfAtt.getNodeName());
//getting Element Name as...."#text"(I am expecting output value "attribute" but it is printing "#text" which i don't know)
System.out.println("Element Attibrute list....."+elementAtt);
//getting Element Attribute list as an...."null"(I am expecting output value object reference but it is printing "null"
(without the rest of the code, i'm guessing that) most likely you are grabbing the first child node of the item element. however, you are not accounting for some text nodes that are most likely in that list, like the whitespace between the item element and the attribute element. please go read some tutorials on xml, there are thousands of them out there, and they will answer all you initial questions much more efficiently than posting each step to the forums. -
How to ignore white space when parse xml document using xerces 2.4.0
When I run the program with the xml given below the following error comes.
Problem parsing the file.java.lang.NullPointerExceptionjava.lang.NullPointerExce
ption
at SchemaTest.main(SchemaTest.java:25)
============================================================
My expectation is "RECEIPT". Pls send me the solution.
import org.apache.xerces.parsers.DOMParser;
import org.xml.sax.InputSource;
import java.io.*;
import org.xml.sax.ErrorHandler;
import org.w3c.dom.*;
public class SchemaTest {
public static void main (String args[])
try
FileInputStream is = new FileInputStream(new File("C:\\ADL\\imsmanifest.xml"));
InputSource in = new InputSource(is);
DOMParser parser = new DOMParser();
//parser.setFeature("http://xml.org/sax/features/validation", false);
//parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "memory.xsd");
//ErrorHandler errors = new ErrorHandler();
//parser.setErrorHandler(errors);
parser.parse(in);
Document manifest = parser.getDocument();
manifest.normalize();
NodeList nl = manifest.getElementsByTagName("organization");
System.out.println((((nl.item(0)).getChildNodes()).item(0)).getFirstChild().getNodeValue());
catch (Exception e)
System.out.print("Problem parsing the file."+e.toString());
e.printStackTrace();
<?xml version = '1.0'?>
<organizations default="detail">
<organization identifier="detail" isvisible="true">
<title>RECEIPT</title>
<item identifier="S100000" identifierref="R100000" isvisible="true">
<title>Basic Module</title>
<item identifier="S100001" identifierref="R100001" isvisible="true">
<title>Objectives</title>
<metadata/>
</item>
</item>
<metadata/>
</organization>
</organizations>
Is there a white space problem? How do I get rid from this problem.ok now i really wrote the whole code, a bit scrolling in the API is to hard?
DocumentBuilderFactory dbf = new DocumentBuilderFactory();
DocumentBuilder db = dbf.newDocumentBuilder();
dbf.setNamespaceAware(true); //or set false
Document d = db.parse(inputstream); -
Problem parsing XML with schema when extracted from a jar file
I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
I get the following exception:
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
I have output the retrieved XML to a file and compared it with my original source and they are identical.
I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
Any suggestions?
The code is as follows:
public void open(File input) throws IOException, CSLXMLException {
InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
builder = factory.newDocumentBuilder();
builder.setErrorHandler(new CSLXMLParseHandler());
} catch (Exception builderException) {
throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
Document document = null;
try {
document = builder.parse(input);
} catch (SAXException parseException) {
throw new CSLXMLException(parseException.toString());
}I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards. -
Parse XML document which have xlink/xpointer inside
dear friends,
There are lots of topic talking about parse xml, validating xml with schema and so on, but no one or any book talking about parsing xml document which can parse document with link inside.
According to Mr Meggison at http://www.megginson.com/Background/
we can do it, but he is not expert with this thing.
For example I have 3 XML document. My main XML document, let named it A.XML have XPointer inside and this element pointing to B.XML and C.XML using xpointer. how to parse A.XML and in the same time my SAX recognized this XPointer and parse also element inside B.XML and C.XML.
I am really grateull for any helpful information from you.
best regardsI think you need to look for a SAX or DOM parser that undestands XPointers and knows how to follow them to additional content.
I have used XSLT and specified external documents to it. It knows how to read a document and in effect make a nodeset which can be searched with the XPath capabilities of XSLT.
It sounds like you wnat an <include file="xxx"/> capability and have the parser stop reading the current file, and start reading the second file.
That works in Schemas, but I'm unaware of any way to do it with SAX or DOM in one pass.
It would not be too hard to process the first file, say with DOM.
After the Document is built, go find the <include> elements, read get the attribute needed, build a new Document and merge it into the original Document in place of the <include> element.
Is this more what you want to do?
Dave Patterson -
XI XML Parser: tag content with "'", single apostrophe: invalid character
Hi all,
we import XML-documents with the file adapter in a sender channel. everything works well.
But if one of the XML-tag contents contains a single apostrophe ( ' ), then the XML parser stops with an error "An invalid character was found inside an entity reference. ". The message can not be processed. If I test the message content in the mapping -> no error.
When the single apostrophe is dereferenced by an additional single apostrophe the XML-File can be processed.
Question: does anybody know how this can be handled because it is not very nice of SAP XI to send single apostrophes in outgoing messages but cannot handle it in incoming messages from other systems? special adapter settings?
Thank you very much
regards
Hanscheck bhavesh reply
Suppress Special Character
also check
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/9420 [original link is broken] [original link is broken] [original link is broken]
Implementing a Java Mapping in SAP PI to remove Escape Sequences from a file -
Help for Parsing XML like HTML Document
I have documents that start with
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
I want to process these documents with a XML Parser.Microsoft XML Parser works well with it.Can I use DOM parser in Java to process such kind of documents?
What Jar file I need to use to access such APIs?Yes, XHTML is XML so you can read it with any XML parser.
And Java already has XML parsers built in. You don't need any jar files. -
Parse XML document ,create table according to tags & load data to table
Hi All!
I have one of the most common problem, one faces when dealing with xml stuff and oracle.I get xml documents, with each file having different tags.I want to write a pl/sql procedure such that, the xml file is parsed, a table is created with the tag names becoming the column names and all the nodes' data get inserted into the table as rows.I am using oracle 10g.
I read a thread at the following url:
Parse XML and load into table
But did not get much of it.
Can anybody please tell me how to accomplish this.
Thanking in advance.
Regards,
Deepika.Why do people have such an aversion to the XML DB forum for XML questions...
See FAQ for XML DB forum here: XML DB FAQ
Explains all about getting XML into tables in the database. -
Parsing XML file with different languages (Xerces)
How do we code or program to an XML file with different
languages , say english and spanish. WHen we parse such a document with the default locale , the presence of special characters throws errors .For eg when I use xerces and use
DOMParser parser = new DOMParser();
try
// Parse the XML Document
parser.parse(xmlFile);
catch (SAXException se)
se.printStackTrace();
org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xfc) was found in the element content of the document.
System Error: void org.apache.xerces.framework.XMLParser.parse(org.xml.sax.InputSource)
So what locale do we set before we parse ?How to handle this problemYou need an encoding attribute in the xml declaration. If you don't, the parser assumes UTF-8, which are ASCII characters up to 127 - useful (only) for English.
So, something like this would allow you to use characters above 127, ISO-8859-1 is the encoding used by standard PCs.
<?xml version="1.0" encoding="ISO-8859-1"?>
You can find a (offical) list of encodings at:
http://www.iana.org/assignments/character-sets
I'm not sure about mixing various encodings. I think you have to resort external parsed entities, which can have their own encoding, but I think you cannot mix encodings in one XML file.
Good luck.
Maybe you are looking for
-
Create GL/AR/AP documents
Hi SAP Experts, I am a technical consultant. I need to test a GST report for that i need some data to create in Development server. Please help me to create GL/AR/AP documents for testing. Regards, kishore
-
2 monitors on 13" MB Pro?
I have tow monitors with the new adpaters but just unboxed my new 13" MB Pro and it only had ONE port.
-
Not Getting Warning Messages in Telesales,but getting the Same in Sales
Hi, I have set the profile oprion "OS: Opportunity Probability Link" to Warning. This should prompt a warning message when the Sales Stage and Win Probalility shold not match,this is happening in Oracle Sales,but the Same Warning Message is not comin
-
Problems moving mails out of Inbox
Hi, We are having problems with a couple of users that occur when they manually move emails out of their Inbox in Outlook; they're complaining that the changes aren't re-conciled to their BB. They are using Curve 8900's. We've tried wiping their BB a
-
Address Book synching only half-works
My iPod Classic seems unable to keep straight which addresses and phone numbers are "home" and which ones are "work", and, though my older iPod Photo could do it, does not seem able to transfer information from the "Notes" field. Is there any solutio