See sample below. Note that although no NS prefix is defined on your sample
XML, I define "ns1" as local prefix for the NS. The prefix (or local name)
does not matter, but the NS the prefix stands for. That's why you would need
to modify your program, if the NS would change in the future.
HTH,
Stefan
using System;
using System.Xml;
namespace TestXmlNsMgr
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string sXml =
@"<?xml version='1.0' encoding='utf-16'?>
<Transfer>
<Config xmlns='http://www.mysite.com/Transfer/'>
<site>NY</site>
</Config>
</Transfer>";
XmlDocument xmlDoc = new XmlDocument();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
XmlNode xmlNode;
try
{
xmlDoc.LoadXml(sXml);
nsMgr.AddNamespace("ns1", "http://www.mysite.com/Transfer/");
xmlNode = xmlDoc.SelectSingleNode("//ns1:site", nsMgr);
Console.WriteLine(xmlNode.InnerXml);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
Console.WriteLine("Press [return] to end program...");
Console.ReadLine();
return;
}
}
}
"Shawn" <bo********@hotmail.com> schrieb im Newsbeitrag
news:O5**************@TK2MSFTNGP12.phx.gbl...
I've read the documentation on XmlNamespaceManager, but I can't figure out
how to implement in my code. Could you please show me an example?
Shawn
"Stefan Misch" <st**********@removethis.gmx.de> wrote in message
news:O7**************@TK2MSFTNGP09.phx.gbl... (1) XPath queries are namespace aware. You must an XmlNamespaceManager in
SelectSingleNode when working with XML documents that use namespaces. For
more information see the online help for XmlNamespaceManager.
(2) xmlns is not a normal attribute, it defines a namespace. If the
namespace changes, it normaly means that the semantics of the XML might
have changed. In your expample <Config> and <site> ar bound to the (default)
namespace "http://www.mysite.com/Transfer/". If this changes to something
other, then you would also need to change your code, where you add the
namespace to the XmlNamespaceManager.
HTH,
Stefan
"Shawn" <bo********@hotmail.com> schrieb im Newsbeitrag
news:e8**************@TK2MSFTNGP10.phx.gbl... > Hi.
> I have an XML file that looks like this:
> <?xml version="1.0" encoding="utf-16"?>
> <Transfer>
> <Config xmlns="http://www.mysite.com/Transfer/">
> <site>NY</site>
> </Config>
> </Transfer>
>
> I'm trying to get the value of "site", but I'm having some trouble with
> it.
> Here is what I've tried so far:
> xmlDoc.DocumentElement.SelectSingleNode("Config/site").InnerXml
> xmlDoc.DocumentElement.SelectSingleNode("Config[@*]/site").InnerXml
>
> The attribute xmlns="http://www.mysite.com/Transfer/" might change in the > future so I need be able to use an XPath expression that will work even if > the value changes.
>
> Thanks,
> Shawn
>
>