Create repeating elements in xml document
Good day,
I have a problem with a project I am busy with. I am creating an XML document from a predefined schema. I am able to this with no problem for one level using this method:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
XmlSerializer serializer = new XmlSerializer(typeof(UKFATCASubmissionFIReport));
TextWriter writer = new StreamWriter(destinationPath);
UKFATCASubmissionFIReport fatcaSub = new UKFATCASubmissionFIReport();
fatcaSub.SchemaVersion = schemaVersion;
//Initialize classes and objects
#region classes and objects
AccountDataType accountData = new AccountDataType();
AccountHolderCodeType accountHolderType = new AccountHolderCodeType();
MessageDataType messageData = new MessageDataType();
MonetaryType moneyType = new MonetaryType();
SubmissionType submissionData = new SubmissionType();
FIReturnActionType fireturnActionData = new FIReturnActionType();
AccountActionType accountActionData = new AccountActionType();
TINCodeType tinCode = new TINCodeType();
HolderTaxInfoType holderInfo = new HolderTaxInfoType();
//PaymentDataType paymentData = paymentDetails();
#endregion
//Monetary type
moneyType.Value = moneyTypeValue;
moneyType.currCode = currCode_Type.GBP;
//Create message data
messageData.FATCAUserId = FatcaUserID;
messageData.XMLTimeStamp = timeStamp;
messageData.MessageCategory = MessageType.NewSubmission;
fatcaSub.MessageData = messageData;
//Create submission data object
submissionData.ReportingPeriod = reportingPeriod;
submissionData.Item = messageRef;
fatcaSub.Item = submissionData;
//FI Return Action
fireturnActionData.Action = ActionType.New;
fireturnActionData.FIReturnRef = returnRef;
//FIReturnActionType[] fireturnItems = new FIReturnActionType[] { fireturnActionData };
//TIN Code Type
tinCode.TINCountryCode = countryCode;
tinCode.Value = tinCodeValue;
tinCode.TINCountryCodeSpecified = itemSpecified;
//TIN Information
holderInfo.ReportableJurisdiction = countryCode;
holderInfo.TIN = holderTIN;
holderInfo.TINCode = tinCode;
//ContactPersonInformation contactInfo = ContactInformation(holderInfo);
//Contact address
ContactAddressType contactAddress = new ContactAddressType();
contactAddress.StreetName = streetName;
contactAddress.City = contactCity;
contactAddress.CountryCode = holderInfo.ReportableJurisdiction;
//Person Details
ContactPersonInformation contactInfo = new ContactPersonInformation();
contactInfo.FirstName = firstName;
contactInfo.LastName = lastName;
contactInfo.Address = contactAddress;
contactInfo.HolderTaxInfo = holderInfo;
contactInfo.BirthDateSpecified = itemSpecified;
contactInfo.BirthDate = dateOfBirth;
PaymentMonetaryType paymentMonetary = new PaymentMonetaryType();
paymentMonetary.currCode = currCode_Type.GBP;
paymentMonetary.Value = paymentValue;
//Payment data object
PaymentDataType paymentData = new PaymentDataType();
paymentData.PaymentCode = PaymentCodeType.Item20;
paymentData.PaymentAmount = paymentMonetary;
//return paymentData;
//Account action
accountActionData.AccountRef = accountRef;
accountActionData.Action = ActionType.New;
//Account information array
//AccountData(paymentData, contactInfo, accountActionData, accountData, accountHolderType);
object[] accountItems = new object[] { accountActionData, accountNumber, paymentData, accountHolderType, contactInfo };
accountData.Items = accountItems;
ItemsChoiceType[] accountFieldNames = new ItemsChoiceType[] { ItemsChoiceType.AccountAction, ItemsChoiceType.AccountNumber, ItemsChoiceType.PaymentData, ItemsChoiceType.AccountHolderType, ItemsChoiceType.Person };
accountData.ItemsElementName = accountFieldNames;
//Financial Information Return main array
//FIReturn(submissionData, fireturnActionData, accountData);
FIReturnType fireturn = new FIReturnType();
object[] fiItems = new object[] { fireturnActionData, fiRegisterID, dueDilligenceInd, thresholdInd, accountData };
fireturn.Items = fiItems;
ItemsChoiceType1[] fiFieldnames = new ItemsChoiceType1[] { ItemsChoiceType1.FIReturnAction, ItemsChoiceType1.FIRegisterId, ItemsChoiceType1.DueDiligenceInd, ItemsChoiceType1.ThresholdInd, ItemsChoiceType1.AccountData };
fireturn.ItemsElementName = fiFieldnames;
FIReturnType[] fiData = new FIReturnType[] { fireturn };
//Map FI return data to submissionData
submissionData.FIReturn = fiData;
//Serialize the submission close the TextWriter
serializer.Serialize(writer, fatcaSub);
writer.Close();
Process.Visible = false;
MessageBox.Show("Processing Complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
Close();
The problem is that I would like fireturn to appear in the document more than once from a dataset. If I changed my code to this:
FIReturnType[] fiData = new FIReturnType[] { fireturn, fireturn, fireturn };
//Map FI return data to submissionData
submissionData.FIReturn = fiData;
I am able to get the three elements as required. How can I change my code to allow for a foreach statement for example?
I managed to change FIReturnType into a list as below. I have a sample datatable also. My code now creates the nodes as expected but the all contain the last item only. What do I need to change so that I get the correct values written?
DataTable dtTable = new DataTable();
dtTable.Columns.Add("FirstName", typeof(string));
dtTable.Columns.Add("Surname", typeof(string));
// Here we add five DataRows.
dtTable.Rows.Add("Test", "Test");
dtTable.Rows.Add("Two", "Three");
dtTable.Rows.Add("Four", "Five");
dtTable.Rows.Add("Six", "Seven");
dtTable.Rows.Add("Eight", "Nine");
List<FIReturnType> fiRetList = new List<FIReturnType>();
foreach (DataRow row in dtTable.Rows)
object fName = row["FirstName"];
object sName = row["Surname"];
contactInfo.FirstName = fName.ToString();
contactInfo.LastName = sName.ToString();
FIReturnType fireturn = new FIReturnType();
object[] fiItems = new object[] { fireturnActionData, fiRegisterID, dueDilligenceInd, thresholdInd, accountData };
fireturn.Items = fiItems;
ItemsChoiceType1[] fiFieldnames = new ItemsChoiceType1[] { ItemsChoiceType1.FIReturnAction, ItemsChoiceType1.FIRegisterId, ItemsChoiceType1.DueDiligenceInd, ItemsChoiceType1.ThresholdInd, ItemsChoiceType1.AccountData };
fireturn.ItemsElementName = fiFieldnames;
fiRetList.Add(new FIReturnType { Items = fiItems, ItemsElementName = fiFieldnames });
FIReturnType[] fiData = fiRetList.ToArray();
submissionData.FIReturn = fiData;
Similar Messages
-
Dynamically Create Repeater Element in ActionScript
Hi,
I'm trying to dynamically create a repeater control with an
image and a label control. I can do it directly in the MXML file
but when I try and covert it into ActionScript it's not working.
Can anyone see what the problem is with my code?
public function GetPalettes():void{
removeChild(document.FrontPage);
Palettes.method = "GET";
params = {"method": "GetPalettes", "BodyPartNo":
document.PalettesMenu.selectedItem.@partNo};
Palettes.cancel();
Palettes.send(params);
var VerticalBox:VBox = new VBox();
VerticalBox.x = 10;
VerticalBox.y = 10;
VerticalBox.id = "VerticalBox";
var PaletteRepeater:Repeater = new Repeater();
PaletteRepeater.dataProvider =
"{Palettes.lastResult.Palette}";
PaletteRepeater.startingIndex = 0;
PaletteRepeater.id = "PaletteRepeater";
var PaletteImage:Image = new Image();
PaletteImage.setStyle("HorizontalAlign", "left");
PaletteImage.source = "
http://localhost/Flex/Personalised%20Palettes-debug/{PaletteRepeater.currentItem.@PictureS rc}Med.png";
PaletteImage.useHandCursor = true;
PaletteImage.buttonMode = true;
PaletteImage.mouseChildren = false;
PaletteImage.id = "PaletteImage";
var PaletteDescription:Label = new Label();
PaletteDescription.text =
"{PaletteRepeater.currentItem.@Description}";
PaletteDescription.id = "PaletteDescription";
document.MainPage.addChild(VerticalBox);
VerticalBox.addChild(PaletteRepeater);
PaletteRepeater.addChild(PaletteImage);
PaletteRepeater.addChild(PaletteDescription);
Thanks"katychapman85" <[email protected]> wrote in
message
news:[email protected]...
> Hey Amy,
>
> I've put a thread up about this but thought I'd ask you
as well as you've
> been
> a great help to me so far.
>
> I have this function:
> public function GetOptions(Menu:int):void{
> document.MenuOptions.url =
> "
http://localhost/Flex/Personalised%20Palettes-debug/MenuOptions.php?Menu=";
> document.MenuOptions.url += Menu;
> document.MenuOptions.send();
> }
>
> What I'm trying to do is when a user clicks on a Radio
button this
> function is
> called and the number of the Menu required is sent to
the function.
>
> I've added this Event Listener to my Radio Button:
>
>
document.RadioButtons2.addEventListener(MouseEvent.CLICK,
> function():void{GetOptions(2);});
>
> However, it's not working. Everything I've read suggests
using an
> anonymous
> function in the Event Listener to pass the menu
parameter but for some
> reason
> it's not working.
What version of Flex are you using? The Help for Flex 3 has
this to say:
http://www.adobe.com/livedocs/flex/3/html/help.html?content=events_05.html
Defining event listeners inline
The simplest method of defining event handlers in Flex
applications is to
point to a handler function in the component's MXML tag. To
do this, you add
any of the component's events as a tag attribute followed by
an ActionScript
statement or function call.
You add an event handler inline using the following syntax:
<mx:tag_name event_name="handler_function"/>
For example, to listen for a Button control's click event,
you add a
statement in the <mx:Button> tag's click attribute. If
you add a function,
you define that function in an ActionScript block. The
following example
defines the submitForm() function as the handler for the
Button control's
click event:
<mx:Script><![CDATA[
function submitForm():void {
// Do something.
]]></mx:Script>
<mx:Button label="Submit" click="submitForm();"/>
Event handlers can include any valid ActionScript code,
including code that
calls global functions or sets a component property to the
return value. The
following example calls the trace() global function:
<mx:Button label="Get Ver" click="trace('The button was
clicked');"/>
There is one special parameter that you can pass in an inline
event handler
definition: the event parameter. If you add the event keyword
as a
parameter, Flex passes the Event object and inside the
handler function, you
can then access all the properties of the Event object.
The following example passes the Event object to the
submitForm() handler
function and specifies it as type MouseEvent:
<?xml version="1.0"?>
<!-- events/MouseEventHandler.mxml -->
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(event:MouseEvent):void {
// Do something with the MouseEvent object.
Alert.show("An event of type '" + event.type + "'
occurred.");
]]></mx:Script>
<mx:Button id="b1" label="Click Me"
click="myEventHandler(event)"/>
</mx:Application>
It is best practice to include the event keyword when you
define all inline
event listeners and to specify the most stringent Event
object type in the
resulting listener function (for example, specify MouseEvent
instead of
Event).
You can use the Event object to access a reference to the
target object (the
object that dispatched the event), the type of event (for
example, click),
or other relevant properties, such as the row number and
value in a
list-based control. You can also use the Event object to
access methods and
properties of the target component, or the component that
dispatched the
event.
Although you will most often pass the entire Event object to
an event
listener, you can just pass individual properties, as the
following example
shows:
<?xml version="1.0"?>
<!-- events/PropertyHandler.mxml -->
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml">
<mx:Script><![CDATA[
import mx.controls.Alert;
private function myEventHandler(s:String):void {
Alert.show("Current Target: " + s);
]]></mx:Script>
<mx:Button id="b1" label="Click Me"
click="myEventHandler(event.currentTarget.id)"/>
</mx:Application>
Registering an event listener inline provides less
flexibility than using
the addEventListener() method to register event listeners.
The drawbacks are
that you cannot set the useCapture or priority properties on
the Event
object and that you cannot remove the listener once you add
it.
don't see anything in there about anonymous functions...? -
Hi Experts,
I am develpoing a program to generate xml file as output. I am using the method CL_IXML and other interfaces to generate the xml data. Here I need to create a root element. I did search in SDN but I couldnot found anything to generate xml root element.
My output should be like this:
<?xml version="1.0" encoding="UTF-8"?>
<Request Version="11.1" IssuerID="1">
<CreatePurchaseRequest
RequestID="123456"
Commonname="test"
</CreatePurchaseRequest>
</Request>
Can anybody plz suggest how can I generate the root element Request here?
Regards,
Ranganadh.Thanks Sandra,
My issue got resolved.
I just created the root element using the method create_sample_element and set the attributes using set_attributes method.
Thanks for your help.
w_ixml = cl_ixml=>create( ).
w_document = w_ixml->create_document( ).
w_root = w_ixml->create_document( ).
IF w_document IS INITIAL.
RAISE EXCEPTION TYPE cx_cmx_da_exception
EXPORTING
textid = cx_cmx_da_exception=>cx_cmx_da_error_internal.
ENDIF.
w_encoding = w_ixml->create_encoding(
character_set = 'utf-8'
byte_order = if_ixml_encoding=>co_none ).
w_document->set_encoding( w_encoding ).
w_element_inv1 = w_document->create_simple_element(
name = 'OrbiscomRequest'
parent = w_document ).
w_element_inv1->set_attribute( name = 'Version'
namespace = ''
value = '11.1' ).
w_element_inv1->set_attribute( name = 'IssuerID'
namespace = ''
value = '1' ). -
How do I create and download an XML document and insert this into a BLOB
I need to create an XMLDOM document and download this onto a users PC. Any ideas about how to do this?
I would prefer to first insert this into a Table (into a BLOB) to allow users to download it later.
I can create an XMLDOM document, I can upload a file into wwv_flow_files and then download this later.
Any suggestion would be appreciated.Douglas,
did you manage to solve this, I am trying to upload an xml file from a page item into the database using a custom pl/sql insert but it won't insert.
Andrew -
How do I retrieve elements in a xml document ?
I would like to know how to retrieve elements from xml document ?
I have created a document already, but how do I proceed from there ?
Also, how do I access the values inside, the attributes and value ?
Thank you.parse the xml file in node wise using compare criteria according to programmer choice u can able to retrieve the elements which u want promptly
-
Creating an xml document from filenames of selected files
Hey guys, I am totally new to automator and applescript so please be kind!
I have an xml/flash image portfolio website which has image galleries. Each gallery has an xml document which specifies a thumbnail and full size photo to be displayed in the gallery. If I want to make a new gallery I have to make a new xml document and enter all the filenames of the images I want to display in the gallery. ( I guess you can see where this is going).
This is fine if I have 10 images in the gallery but if I want to make a gallery with 350 images in then it could get pretty tedious.
What I would love to be able to do is select a group of images and then have a script or automator action that can copy the files names and create a new gallery xml document containing the relevant code with all the files names. Ideally then saving the gallery with a sequential filename.
Tying this into the new contextual services menu in snow leopard would really make the task incredibly easy.
Is this possible? I'm not scared of learning how to do this therefore some pointers in the right direction would be great.
Thanks,
ChrisThanks Camalot,
I was just thinking of selecting images from the finder but if this could be integrated into Aperture's export dialog that would be even better.
this is the xml:
<?xml version="1.0" encoding="utf-8"?>
<gallery thumbwidth="220" thumbheight="138" columns="3" gap="4">
<item>
<ID>1</ID>
<title><![CDATA[Title 1]]></title>
<desc><![CDATA[This is description 1. <font color="#0099CC">This is a colourful text. </font> This is a <a href="http://www.flashden.net/user/iceonflames">link</a>. <i>This is italic text.</i> <b>This is bold text.</b> <b><i>This is bold italic text.</i></b> This text is styled by a CSS document.<br/><br/>]]></desc>
<thumb>images/thumbs/7.jpg</thumb>
<image>images/big/7.jpg</image>
</item>
<item>
<ID>2</ID>
<thumb>images/thumbs/8.jpg</thumb>
<image>images/big/8.jpg</image>
</item>
<item>
<ID>3</ID>
<title><![CDATA[Title 3]]></title>
<desc><![CDATA[This is description 3. <font color="#0099CC">This is a colourful text. </font> This is a <a href="http://www.flashden.net/user/iceonflames">link</a>. <i>This is italic text.</i> <b>This is bold text.</b> <b><i>This is bold italic text.</i></b> This text is styled by a CSS document.<br/><br/>]]></desc>
<thumb>images/thumbs/9.jpg</thumb>
<image>images/big/9.jpg</image>
</item>
</gallery> -
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
For the last 5 years (and in IPCC3.x/4.x,UCCX/5.x/7.x) I've used the same basic subflow to read a XML document that contains holiday dates where the queue should be closed. I've re-used this script on 20+ client installs and it's always worked. The structure of the script allows you to pass the path and filename of the XML document as parameters to the subflow. (The document is in the repository)
I loaded this script in UCCX 8.0.2 recently and it crashed with a Java.IO error. It looked like it was trying to read the file system directly and not the repository. (In the Linux appliance model this kind of makes sense but why is the step trying to read the file system directly?)
So I open a TAC case (SR# 615243125) and TAC tells me that the method of using the Create File Document step is not supported anymore and that I should specify the filename directly in the Create XML Document step
The problem that I see (aside from having to edit all my scripts that use XML files) is that the Create XML Document step is looking for the input to be a type DOCUMENT and not a type STRING. This seems to imply that I have to hardcode the document in each script that I deploy for a customer. When it was a string it was easy to construct the full file path from parameters and pass to the subflow.
Questions to the group
#1 Am I missing something here?
#2 Do you assume that you'll be able to load a script that worked fine in UCCX 7 into UCCX 8 and that it should completely function when you're doing everything according to the step reference documentation.
#3 Cisco didn’t document this in any way that I can find.
#4 How can you use the Create XML Document step in a fashion that would let you construct the path of the file and the filename previously in the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
(Background)
Create File Document Step
The input filename is a STRING, could be an explicit path and filename in the repository or a variable that represents that path and string
The output of this step is a DOCUMENT to be used in the Create XML Document step
The string FILE_FullPathHolidayFiles references en_us\folderName\documentName.xml
The document was properly uploaded into the repository only, NOT trying to directly read c:\foo\blah…
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
The create XML document input can only be a type DOCUMENT#1 Am I missing something here?
You are mixing two different issues together here.
The Create File Document step is indeed not needed or supported for creating an XML document. That is why there is a unique step; to trigger XML parsing within the MIVR subsystem.
Accessing the file system is restricted to a single folder within the VOS model (i.e. 8.0+). This folder is not backed up, replicated, or cleaned up automatically. It was intended to give developers some FS access as a temporary swap location only.
#2 Do you assume that you'll be able to load a script that
worked fine in UCCX 7 into UCCX 8 and that it should completely
function when you're doing everything according to the step reference
documentation.
Assume nothing; read the documentation and attend one of the dozens of partner training sessions that CCBU put on advising of the upcoming changes.
#3 Cisco didn’t document this in any way that I can find.
You're right, I guess, on the Create File vs. XML Document step. AFAIK Cisco never wrote a notice into the Step Reference Guide explicitly stating that you cannot use the Create File Document although the documentation seemed pretty clear to me without it. File system restrictions are documented in the 8.0 release notes.
Scripting and Development Series: Volume 2, Editor Step ReferenceUse the Create XML Document step to create a logical document that maps a document to another document variable (where the document has already been pre-parsed as an XML document and is ready to be accessed by the Get XML Document Data step).Use this step before the Get XML Document Data step to obtain data from a document formatted using the Extensible Markup Language (XML).
#4 How can you use the Create XML Document step in a fashion that would
let you construct the path of the file and the filename previously in
the script so you could pass it to a subflow ? It would seem this functionality has been killed in UCCX 8
No it hasn't; just concatinate a string to build the Source Document parameter the step needs. Example: "DOC[" + myFilePath + "]" -
How to extract the nodes of any given XML document ???
Hello,
Greetings! It is an interesting forum.
A Snippet of XML Schema PurchaseOrder.xsd as given in user guide is as follows
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb"
version="1.0" xdb:storeVarrayAsTable="true">
<xs:element name="PurchaseOrder" type="PurchaseOrderType"
xdb:defaultTable="PURCHASEORDER"/>
<xs:complexType name="PurchaseOrderType" xdb:SQLType="PURCHASEORDER_T">
<xs:sequence>
<xs:element name="Reference" type="ReferenceType" minOccurs="1"
xdb:SQLName="REFERENCE"/>
<xs:element name="Actions" type="ActionsType" xdb:SQLName="ACTIONS"/>
<xs:element name="Reject" type="RejectionType" minOccurs="0"
xdb:SQLName="REJECTION"/>
<xs:element name="Requestor" type="RequestorType"
xdb:SQLName="REQUESTOR"/>
<xs:element name="User" type="UserType" minOccurs="1"
xdb:SQLName="USERID"/>
<xs:element name="CostCenter" type="CostCenterType"
xdb:SQLName="COST_CENTER"/>
<xs:element name="ShippingInstructions" type="ShippingInstructionsType"
xdb:SQLName="SHIPPING_INSTRUCTIONS"/>
<xs:element name="SpecialInstructions" type="SpecialInstructionsType"
xdb:SQLName="SPECIAL_INSTRUCTIONS"/>
<xs:element name="LineItems" type="LineItemsType"
xdb:SQLName="LINEITEMS"/>
</xs:sequence>
</xs:complexType>
full schema is available in url
http://download-west.oracle.com/docs/cd/B12037_01/appdev.101/b10790/xdb03usg.htm#BABBGIED
The views use XPath expressions and functions such as extractValue() to define the mapping between columns in the view and nodes in the XML document. The following view is created on purchase order schema.
Creating Relational Views On XML Content
CREATE OR REPLACE view PURCHASEORDER_MASTER_VIEW
(REFERENCE, REQUESTOR, USERID, COSTCENTER,
SHIP_TO_NAME,SHIP_TO_ADDRESS, SHIP_TO_PHONE,
INSTRUCTIONS)
AS
SELECT extractValue(value(p),'/PurchaseOrder/Reference'),
extractValue(value(p),'/PurchaseOrder/Requestor'),
extractValue(value(p),'/PurchaseOrder/User'),
extractValue(value(p),'/PurchaseOrder/CostCenter'),
extractValue(value(p),'/PurchaseOrder/ShippingInstructions/name'),
extractValue(value(p),'/PurchaseOrder/ShippingInstructions/address'),
extractValue(value(p),'/PurchaseOrder/ShippingInstructions/telephone'),
extractValue(value(p),'/PurchaseOrder/SpecialInstructions')
FROM PURCHASEORDER p;
When we register XML Schema in Oracle 9i, the schema elements of XML documents are stored as XMLType, that is, stored using object-relational storage techniques.
For a small schema, we could build the above view manually, but for large/nested schema, if we have query to build XML documents node list, it will help us to build Relational Views on XML Content.
How do we extract the nodes of any given XML document through O-R structures or XML DB using XML DB functions?
Any alternate thoughts are welcome.
I appreciate your help.
Regards
RamRam
Once again, I do not think that you can solve the problem you are trying to solve. Fundamentally you need to determine for a given element of a given complex type what are it's child elements. For each of those elements you then need to find out whether or not it in turn has child elements...
Then you have to think about elements defined as ref rather than type, elements that are substituteable, and the rest of possibilities that can be described with XML Schema.
If you can solve that problem you're a better man than I as the saying goes. Anyone rather than give you a fish, I'll show you how to at least put a worm on the hook..
The following query gets the names of the elements inside a each of the global complex types
Good luck, if you come up with a query to do this I'd love to see it...
SQL> column COMPLEX_TYPE format A32
SQL> column ELEMENT format A32
SQL> --
SQL> select extractvalue
2 (
3 value(ct),
4 '/xs:complexType/@name',
5 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
6 ) COMPLEX_TYPE,
7 extractvalue
8 (
9 value(et),
10 '/xs:element/@name',
11 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
12 ) ELEMENT
13 from resource_view,
14 table
15 (
16 xmlsequence
17 (
18 extract
19 (
20 res,
21 '/r:Resource/r:Contents/xs:schema/xs:complexType',
22 'xmlns:r="http://xmlns.oracle.com/xdb/XDBResource.xsd"
23 xmlns:xs="http://www.w3.org/2001/XMLSchema"')
24 )
25 ) ct,
26 table
27 (
28 xmlsequence
29 (
30 extract
31 (
32 value(ct),
33 '/xs:complexType/*/xs:element',
34 'xmlns:xs="http://www.w3.org/2001/XMLSchema"'
35 )
36 )
37 ) et
38 where equals_path(res,'/home/SCOTT/poSource/xsd/purchaseOrder.xsd') = 1
39 /
COMPLEX_TYPE ELEMENT
-------------------------------- ------------------------PurchaseOrderType Reference
PurchaseOrderType Actions
PurchaseOrderType Reject
PurchaseOrderType Requestor
PurchaseOrderType User
PurchaseOrderType CostCenter
PurchaseOrderType ShippingInstructions
PurchaseOrderType SpecialInstructions
PurchaseOrderType LineItems
LineItemsType LineItem
LineItemType Description
LineItemType Part
ActionsType Action
RejectionType User
RejectionType Date
RejectionType Comments
ShippingInstructionsType name
ShippingInstructionsType address
ShippingInstructionsType telephone
19 rows selected. -
Creating an Element for an XML Document
Assuming I have an XML file
file.xml
<root>
<child1>
<child2>
<child100>
<root>
i do
SAXBuilder parser = new SAXBuilder();
doc = parser.build(file);
root = doc.getRootElement();This returns a root elemnet for the entire tree.Now my question is how do i create a root element for say jus the top 10 children? That is, is there a way i can create a document just reading the first 10 elements from the file tree above so that when i do a getChildren on root I should have only 10 elements in the list.| 1. How are the attributes of an XML element can be stored to the database
XML SQL Utility (which XSQL uses under the covers) only stores
documents in the canonical format. You'll need to use an XSLT
transformation to transform data into the canonical format
(including transforming attribute values into elements whose
names correspond to the column in which you'd like to store it)
| 2. How can I store a single XML document to multiple database tables?
I outline several techniques for this in my upcoming
O'Reilly book, "Building Oracle XML Applications".
The basic idea is to either:
(1) Use an Object View with an INSTEAD OF INSERT trigger, or
(2) Use a technique that transform the inbound document
into a multi-table insert-format and passes each
relevant part for insert to the XML SQL Utility separately.
null -
Identify individual elements in repeated elements in an XML document
Hello,
I'd like to identify individual elements in repeated elements in an XML document.
For example a table 'dataXML' which has a column 'sample' (XMLType). If I have an XML document such as,
<ELEMENT>
<PO>
<PONO>100</PONO>
<PONO>200</PONO>
</PO>
</ELEMENT>
I can use //PONO[1] to identify the first "PONO" element (with value 100) and //PONO[2] to identify the second "PONO" element in the document.
If I write this query:
select L.sample.extract('ELEMENT/PO/PONO/text()')).getStringVal()"SAMP"
from dataXML L
I'll receive this result:
SAMP
100200 (the first row)
And if I write this query:
select L.sample.extract('ELEMENT/PO/PONO[1]/text()')).getStringVal()"SAMP"
from dataXML L
I'll receive this result:
SAMP
100 (the first row)
But I'd like the following result:
SAMP
100 (the first row)
200 (the second row).
Could you help me, please?
Thank you very much.
Melissa Lemosyou have to use something like this.
select extractvalue(xmltype_column, '/Name/@attributename')
from table_name
For more details see
XMLDB Developers Guide (Oracle 9i)
Chapter - XPATH and namespace Primer
Table C2 - Location Path Examples Using Abbreviated Syntax.
Page Number 907/1044
Hope this helps. -
How to get the count of repeating elements in a xml doc.
In many xml documents, in is common to have repeating child elements and what I would like to know is how do I determine exactly how many of these child elements exist in a particular document. There is probably a correct XPath string to determine this, but I cannot figure out what it is. Here is an example
<a>
<b>
<c>1</c>
<c>5</c>
<c>22</c>
</b>
</a>
The above 'c' element is what varies in number from document to document and I need to know how to get the number of 'c' elements for the document, which would be 3 in the above case.create table test_xml(data xmltype)
insert into test_xml values(
xmltype('<a>
<b>
<c>1</c>
<c>5</c>
<c>22</c>
</b>
</a>')
select extract(data, '/a/b/c').getclobval() from test_xml
select count(*) from test_xml
where existsnode(data, '/a/b/c')=1
good luck. -
Heap space error while creating XML document from Resultset
I am getting Heap space error while creating XML document from Resultset.
It was working fine from small result set object but when the size of resultset was more than 25,000, heap space error
I am already using -Xms32m -Xmx1024m
Is there a way to directly write to xml file from resultset instead of creating the whole document first and then writing it to file? Code examples please?
here is my code:
stmt = conn.prepareStatement(sql);
result = stmt.executeQuery();
result.setFetchSize(999);
Document doc = JDBCUtil.toDocument(result, Application.BANK_ID, interfaceType, Application.VERSION);
JDBCUtil.write(doc, fileName);
public static Document toDocument(ResultSet rs, String bankId, String interfaceFileType, String version)
throws ParserConfigurationException, SQLException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("sims");
results.setAttribute("bank", bankId);
results.setAttribute("record_type", "HEADER");
results.setAttribute("file_type", interfaceFileType);
results.setAttribute("version", version);
doc.appendChild(results);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
String columnName="";
Object value;
while (rs.next()) {
Element row = doc.createElement("rec");
results.appendChild(row);
for (int i = 1; i <= colCount; i++) {
columnName = rsmd.getColumnLabel(i);
value = rs.getObject(i);
Element node = doc.createElement(columnName);
if(value != null)
node.appendChild(doc.createTextNode(value.toString()));
else
node.appendChild(doc.createTextNode(""));
row.appendChild(node);
return doc;
public static void write(Document document, String filename) {
//long start = System.currentTimeMillis();
// lets write to a file
OutputFormat format = new OutputFormat(document); // Serialize DOM
format.setIndent(2);
format.setLineSeparator(System.getProperty("line.separator"));
format.setLineWidth(80);
try {
FileWriter writer = new FileWriter(filename);
BufferedWriter buf = new BufferedWriter(writer);
XMLSerializer FileSerial = new XMLSerializer(writer, format);
FileSerial.asDOMSerializer(); // As a DOM Serializer
FileSerial.serialize(document);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
//long end = System.currentTimeMillis();
//System.err.println("W3C File write time :" + (end - start) + " " + filename);
}you can increase your heap size..... try setting this as your environment variable.....
variable: JAVA_OPTS
value: -Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m -
ClassCastException while creating an XML document in servlet
HI,
I am trying to create an XML document in a servlet and I am getting ClassCastException at runtime when casting org.w3c.dom.document to org.apache.crimson.tree.XmlDocument . I am using Tomcat 4.1
The same code is working fine when executed in a stand alone java program
Can anyone please help me in trying to solve this problem. I require it urgently.
The following is my code:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.crimson.tree.XmlDocument;
public class test{
public void createxml (String username) throws Exception
Document doc=null;
DocumentBuilderFactory dbf=null;
DocumentBuilder db=null;
Element root=null;
Element poline=null;
org.apache.crimson.tree.XmlDocument xmldoc=null;
FileOutputStream fos=null;
dbf = DocumentBuilderFactory.newInstance ();
db = dbf.newDocumentBuilder ();
doc = db.newDocument ();
root = doc.createElement ("album");
doc.appendChild (root);
poline= doc.createElement("album-name");
root.appendChild(poline);
//I am getting the ClassCastException in this statement
xmldoc = (XmlDocument) doc;
fos = new java.io.FileOutputStream("xyz.xml");
xmldoc.write(fos);
fos.close();
}I am not too much of an expert on this issue, but I did a search. Maybe this page can help or point you in the right direction.
http://www.jspwiki.org/Wiki.jsp?page=A2AClassCastException
I hope this helps. -
How to create an XML document from a String.
Can anyone help,
In the Microsoft XML Document DOM there is a load function load(string) which will create an XML document, but now we are switching to Java and I do not know how to create and XML document from a string, this string �xml document� is passed to my program from a webservice and I need to read several xml elements form it in a web server.
This string is a well formatted XML document:
<?xml version="1.0" encoding="UTF-8"?>
<Countries NumberOfRecords="1" LanguageID="en-us">
<Country>
<CountryCode>AU</CountryCode>
<CountryName>AUSTRALIA</CountryName>
</Country>
</Countries>Thanks PC!
I made it work using:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
factory.setIgnoringComments(true); // We want to ignore comments
// Now use the factory to create a DOM parser
DocumentBuilder parser = factory.newDocumentBuilder();
//TransformThisStringBuffer is a string buffer wich contain the 'XML document (String)'
InputStream in = new ByteArrayInputStream(TransformThisStringBuffer.toString().getBytes());
// Parse the InputStream and build the document
Document document = parser.parse(in);
But which one is faster InputSource or InputStream, were would you put the "new InputSource(new StringReader(yourString))" in the above code? -
Append XML elements with same name in an XML document
Hi,
I am using Oracle9i XMLDB utilities to modify an XML document stored in the database. I have a sample XML document like this in the database:
<Person>
<Address ID="1"> </Address>
</Person>
My task is to include a second <Address> element with a different attribute so that my XML document will become
<Person>
<Address ID="1"> </Address>
<Address ID="2"> </Address>
</Person>
After creating the second element, I am using the function xmldom.appendChild() or xmldom.insertBefore() but they remove the first <Address> element and replace it with the second one. This is not what I want since I want both <Address> elements to be present.
Could anyone please advise.
Thanks.
A. DennisPlease post your question [url http://forums.oracle.com/forums/forum.jsp?forum=154]here for quick response.
thank you.
Regards,
Anupama
[url http://otn.oracle.com/sample_code/]OTN Sample Code
Maybe you are looking for
-
Characteristic relationship with Exit class is not applied correctly
We are using a characteristic relationship (with derivation) type Exit class. For that we have created class ZCL_RSPLS_ARTICLE_FROM_PLMOD as a copy of the standard class CL_RSPLS_CR_EXIT_BASE. Target and source characteristics are members of the aggr
-
Is there any way to retrieve a previous backup after the reset version has backed up?
My phone recently freaked out and went into safe mode and when i went to back it up to the most recent back up, i accidentally set it up as a new iphone.. then it backed up to my computer which erased the most recent back up i wanted... Is there any
-
Error on every startup - after installing LR 5
Lightroom encountered an error when reading from its preview cache and needs to quit. Lightroom will attempt to fix this problem the next time it launches. It then quits - restarts - and shows the message again - how do I get rid of that error? OS: M
-
Vendor Invoice - FB60 (simulation - add new column in display overview)
Hi experts, Requirements: Upon FB60 simulation, Display Overview Screen to Add new column of Internal Order Description to the Line Item ALV grid display. Environment: ECC5, Program in scope: SAPMF05A, Tcode in scope: FB60 Changes done (not in sequen
-
UNICODE Issue in DB Scripts (need a work around in SQLCMD IN SSMS)
Hi, i need help to resolve the below issue from expects, Currently i am using SQLCMD mode in SSMS to execute multiple DB Scripts in single execution as below :CONNECT <SQLSERVER> GO GO :r "D:\test1.sql" GO :r "D:\test2.sql" GO :r "D:\test3.sql" in ou