add a child element using c#

  • Thread starter Thread starter Claudia Fong
  • Start date Start date
C

Claudia Fong

Hi,

I have a xml document which is like this:

<profile document>
<Child name = profile1 id = 1>
</Child>
</profile document>


I want to add another element into this one and what is doing right now
with my code is overwrite the existing element... can someone help me?

<profile document>
<Child name = profile1 id = 1>
</Child>
<Child name = profile2 id = 2>
</Child>
</profile document>


XmlElement ChildElement =
parent.OwnerDocument.CreateElement(ChildElementName);
ChildElement.SetAttribute(ChildNameAttributeName, Child.Name);
ChildElement.SetAttribute(ChildIDAttributeName, Child.ID);

parent.AppendChild(ChildElement);

Cheers!

Claudi
 
Claudia said:
I have a xml document which is like this:

<profile document>
<Child name = profile1 id = 1>
</Child>
</profile document>

That is not an XML document as spaces inside element names (e.g "profile
document") are not allowed and as attribute values need to be quoted.
I want to add another element into this one and what is doing right now
with my code is overwrite the existing element... can someone help me?

<profile document>
<Child name = profile1 id = 1>
</Child>
<Child name = profile2 id = 2>
</Child>
</profile document>


XmlElement ChildElement =
parent.OwnerDocument.CreateElement(ChildElementName);
ChildElement.SetAttribute(ChildNameAttributeName, Child.Name);
ChildElement.SetAttribute(ChildIDAttributeName, Child.ID);

parent.AppendChild(ChildElement);

I don't see how that code could overwrite an existing element as you
create a new element and append it.
What lacks is e.g.
parent.OwnerDocument.Save("file.xml");
to persist the changes made.
 
Hi,

I have a xml document which is like this:

<profile document>
<Child name = profile1 id = 1>
</Child>
</profile document>

I want to add another element into this one and what is doing right now
with my code is overwrite the existing element... can someone help me?

<profile document>
<Child name = profile1 id = 1>
</Child>
<Child name = profile2 id = 2>
</Child>
</profile document>

XmlElement ChildElement =
parent.OwnerDocument.CreateElement(ChildElementName);
ChildElement.SetAttribute(ChildNameAttributeName, Child.Name);
ChildElement.SetAttribute(ChildIDAttributeName, Child.ID);

parent.AppendChild(ChildElement);

Cheers!

    Claudi

*** Sent via Developersdexhttp://www.developersdex.com***

Hi,

It's impossible that you have that document. It's not a valid XMl
document, by far.

After that, how are you keeping your document in memory?
If you are using XmlDocument use the AppendChild method
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top