473,654 Members | 3,239 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Appending XML to existing XmlDocument

I have a database class that maintains data about customers i my system.
The basic XML for this looks like:

<Chunk>
<Vendor>
<Database/>
</Vendor>
</Chunk>

When a user is to be registrered in the system, XML like this is created
in a seperate XML-class (Xml):

<User>
<UserName>stoch olm</UserName>
<NumberOfItemsB ought>0</NumberOfItemsBo ught>
<SignOfLastImag e>A31A20AB338B6 F2FD772ECFA0</SignOfLastImage >
<n>DB1A46496C83 DFFC0CA2BA91585 AA25E90195B77DB 5997DA3D</n>
<e>AAB7E2A0F</e>
</User>

This piece of XML should be appended as a child of the element "User"
such that the XML will look like this:

<Chunk>
<Vendor>
<Database>
<User>
<UserName>stoch olm</UserName>
<NumberOfItemsB ought>0</NumberOfItemsBo ught>
<SignOfLastImag e>A31A20AB338B6 F2FE</SignOfLastImage >
<n>B1A46496C83D FFC0CA2BA91585A A25E90195B77DB5 997</n>
<e>AAB7E2A0F</e>
</User>
</Database>
</Vendor>
</Chunk>

But how do I insert the new piece of XML via DOM? My base xml is loaded
in an XmlDocument object, and the new XML is created like this in my Xml
class:

public static XmlNode CreateXmlForDat abase(
string userName,string n,string e,string signOfLastImage
)
{
XmlDocument xDoc = new XmlDocument();
XmlNode node = xDoc.CreateNode (XmlNodeType.El ement,"User",nu ll);
XmlElement elem = xDoc.CreateElem ent(null,"UserN ame",null);
elem.InnerText = userName;
node.AppendChil d(elem);
elem = xDoc.CreateElem ent(null,"Numbe rOfItemsBought" ,null);
elem.InnerText = "0";
node.AppendChil d(elem);
elem = xDoc.CreateElem ent(null,"SignO fLastImage",nul l);
elem.InnerText = signOfLastImage ;
node.AppendChil d(elem);
elem = xDoc.CreateElem ent(null,"n",nu ll);
elem.InnerText = n;
node.AppendChil d(elem);
elem = xDoc.CreateElem ent(null,"e",nu ll);
elem.InnerText = e;
node.AppendChil d(elem);
return node;
}

If I try with this in my database class:

XmlNode node = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode newUser = _xDoc.SelectSin gleNode("/Chunk/Vendor/Database");
newUser.AppendC hild(node);

I get the error

"The node to be inserted is from a different document context."

Why is that?

The base XML in my database class is initialized as

static XmlDocument _xDoc = new XmlDocument();
_xDoc.LoadXml(" <Chunk><Vendor> <Database/></Vendor></Chunk>");

I hope you can help me out on this one,

Thanks, :o)

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.
Nov 15 '05 #1
4 18173
Jesper Stocholm <j@stocholm.inv alid> wrote:

<snip>
If I try with this in my database class:

XmlNode node = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode newUser = _xDoc.SelectSin gleNode("/Chunk/Vendor/Database");
newUser.AppendC hild(node);

I get the error

"The node to be inserted is from a different document context."


The easiest way to get away from this is to pass the XmlDocument you'll
be including it in to CreateXmlForDat abase rather than creating an
XmlDocument within the method. However, you could also use the
XmlDocument.Imp ortNode method - see the details within MSDN for more
information.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Jon Skeet [C# MVP] wrote :

Hi Jon, thanks for your prompt reply,
Jesper Stocholm <j@stocholm.inv alid> wrote:
If I try with this in my database class:

XmlNode node = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode newUser = _xDoc.SelectSin gleNode("/Chunk/Vendor/Database");
newUser.AppendC hild(node);

I get the error

"The node to be inserted is from a different document context."


The easiest way to get away from this is to pass the XmlDocument you'll
be including it in to CreateXmlForDat abase rather than creating an
XmlDocument within the method. However, you could also use the
XmlDocument.Imp ortNode method - see the details within MSDN for more
information.


I have tried with ImortNode-method, and it nicely imports the data from
the new XmlDocument ... only it is at the wrong place.

My code is this:

XmlDocument newUser = new XmlDocument();
newUser = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode nodeUser = _xDoc.ImportNod e(newUser.Selec tSingleNode
("User"),tru e);
_xDoc.DocumentE lement.AppendCh ild(nodeUser);

The Xml should look like

<Chunk>
<Vendor>
<Database>
<User>
<UserName>stoch olm</UserName>
...
</User>
</Database>
</Vendor>
</Chunk>

But it is now

<Chunk>
<Vendor>
<Database/>
</Vendor>
<User>
<UserName>stoch olm</UserName>
...
</User>
</Chunk>

How can I make it import the XML-chunk as a child of the Database-
element?

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.
Nov 15 '05 #3
Jesper Stocholm <j@stocholm.inv alid> wrote:
My code is this:

XmlDocument newUser = new XmlDocument();
newUser = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode nodeUser = _xDoc.ImportNod e(newUser.Selec tSingleNode
("User"),tru e);
_xDoc.DocumentE lement.AppendCh ild(nodeUser);
<snip>
How can I make it import the XML-chunk as a child of the Database-
element?


Just append it as a child of the appropriate element. You're calling
DocumentElement .AppendChild, so it's appending it to the
DocumentElement (which is <Chunk>). There are any number of ways of
getting to the right node (e.g. XPath, straight DOM manipulation etc).
Once you've got the right node, just call AppendChild on that, instead
of the DocumentElement .

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
Jesper Stocholm wrote :
Jon Skeet [C# MVP] wrote :

The easiest way to get away from this is to pass the XmlDocument
you'll be including it in to CreateXmlForDat abase rather than
creating an XmlDocument within the method. However, you could also
use the XmlDocument.Imp ortNode method - see the details within MSDN
for more information.


I have tried with ImortNode-method, and it nicely imports the data
from the new XmlDocument ... only it is at the wrong place.

How can I make it import the XML-chunk as a child of the Database-
element?


I found the answer myself. This code does the trick:

XmlDocument newUser = new XmlDocument();
newUser = Xml.CreateXmlFo rDatabase(usern ame,n,e,SignOfL astImage);
XmlNode nodeDatabase = _xDoc.SelectSin gleNode("/Chunk/Vendor/Database");
XmlNode nodeUser = _xDoc.ImportNod e(newUser.Selec tSingleNode("Us er"),true);
nodeDatabase.Ap pendChild(nodeU ser);

:o)

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1499
by: Kleist | last post by:
Hello, I use DOM XML PHP functions to build a document. Is it possible to insert a new node as sibling right after the selected by xpath node? There is a function insert_before() but it seems that it appends a child? TIA, K.
3
4994
by: ArmsTom | last post by:
I know this question has been asked several times over. For some reason I cannot get it to sink in. I would like to create a xml document fragment (<--I think that's what I want, tell me if I'm wrong) that "looks" like this: <Level1 att=? att2=? att3=?> <Level2a> <Level3a/> <Level3b/>
1
4236
by: Novice | last post by:
Hey all, I've read a few articles about speed and XML processing - so I just want to make sure that I'm using the right strategy for what I want to achieve. I have an XML file that I'm appending to every time a user submits their information. Right now I'm using XMLDocument (Load and Save) in conjuncture with XmlElement objects.
8
5782
by: yinjennytam | last post by:
Hi all, I'm new to .NET and XML and I have a question. Given an XML file, I want to navigate its content and look for one or two particular elements to get their values. At this point, it suffices to open the XML file for read-only access. Once I have processed these values, I might need to update a bunch of subelements of a certain element. For example, I may need to update the Field Name attribute plus the DataField element value...
2
3594
by: Cat | last post by:
How do you go about appending data from a dataset to an existing xml file? I know you can use WriteXML but this writes over any data already existing in the specified file.. Cat
2
16713
by: feng | last post by:
I think I didn't phrase my quetion clear enough in the last post. Here is what I need: In my VB.Net code, I already have a XML created in XMLDocument formate. I can also convert it into a string using the innerXML property of the XMLDocument object. What I want is to write this existing string, or XMLDocument, into a file, for instance, c:\test.xml. So as you can see, XMLWritter doesn't help me here,
13
2608
by: sherifffruitfly | last post by:
Hi all, I'm trying to distill all of the info from google searches into what I need, with partial success. In truth, the whole xmlNode, Document, Element, etc group of classes & methods is going over my head - lol! The structure of the xml file I'm trying to append to is as follows: <?xml version="1.0" encoding="UTF-8"?> <!-- stuff -->
2
5505
by: Phil Galey | last post by:
I'm using the followg code to add the attribute overwrite='true" to a select list of XML tags in an XML document. The document is loaded from a file and just the tags with names matching what's in the ArrayList are updated to contain the new attribute. However, after it saves back to the XML file, I find that only the last one in the list was updated and all the ones prior to the last one in the loop are skipped. Why is it losing the updates...
3
3902
by: Stephen Ward | last post by:
I have a simple little project open a xml file change a few nodes save the file, no big deal. The problem is that the doctype is getting modified when I save the file. So it looks like this: <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> But when I save it : <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
0
8379
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8294
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7309
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1924
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.