XML Processing and c#

  • Thread starter Thread starter Tarun Mistry
  • Start date Start date
T

Tarun Mistry

Hi all, just looking for a little guidance with xml procerssing.

Imagine the scenario, I have a XmlDocument object populated with XML. I need
to find and replaces some of the text in one of the nodes, i.e. the basic
XML below, I want to substitute _replace_with_value_ with some data,

<root>
....
<tag>_replace_with_value_</tag>
....
</root>

What is the process for doing this. I can find the node using
SelectSingleNode, however this extracts it into a new NodeElement, what do I
need todo to perform a simple search and replace on my main document object?

Thanks,

Kind regards
Taz
 
SelectSingleNode does not extract the node into a new XmlNode. It
returns the node from the document that matched the selection criteria.

So, if you say:

XmlNode tagNode = doc.SelectSingleNode("root/tag");
tagNode.InnerText = "changed";

then the contents of the tag within the XML document doc will change to
"changed". tagNode is a reference into the XmlDocument, not a copy.
 
Many thanks Bruce, problem solved. However a further question to increase my
understanding, why does a namespace object have to be given to the
SelectSingleNode member before executing?

i.e.

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("xsi", http://www.w3.org/2001/XMLSchema-instance);

what does this achieve?

Thanks again,
Taz
 
Namespaces in XML server pretty much the same purpose as they do in .NET
Framework. They serve to disambiguate between element tag names that may be
the same but belong to different groups. That's the short answer, if you
really wnat to get farther into XML the Quickstarts has some samples and MSDN
Online has extensive documentation.
Peter
 
Hi,
this might be useful in some scenarios like when you have a new child with
which you want to replace with your old child node. as well, it will help
you to replace a old child in a document with new child from some other
document,

XmlNode node = doc.SelectSingleNode("//root/firstchild");

XmlNode node1 = doc.SelectSingleNode("//root/secondchild");

node.ParentNode.ReplaceChild(node1,node);

If you have a new child element - node1 is from other document then

node.ParentNode.ReplaceChild(doc..ImportNode(node1,true), ,node);

HTH,
 
And it is only required when you are using some elements with some prefix
like myns:mynode then myns must be tied with some namespace so you have to
use namespace in that scenario only else no namespace is required and its
only purpose is to distinguish the elements with the same name [if it is
there] from different namespaces like what Namespace in .Net serves the
purpose....
Agree with Peter,

HTH,
 
Many thanks everyone!

I really appreciate your help and input.

Everything is much clearer now.

Kind regards
Tarun
 
Back
Top