XPathNavigation and Namespaces.

I have the following code that is attempting to read nodes from an xml
file...

XmlDocument xpdStatus = new XmlDocument();
xpdStatus.Load("status.xml");
XPathNavigator xpnStatus = xpdStatus.CreateNavigator();

XPathNodeIterator xpniStatus = xpnStatus.Select("descendant::Status");
while (xpniStatus.MoveNext())
{
Console.WriteLine("Book title:  {0}", xpniStatus.Current.Value);
XmlNode node = ((xpniStatus.Current) as IHasXmlNode).GetNode();
Console.WriteLine("Status:  {0}", node.Value);
}

The code works fine until I attempt to add namespaces, with prefixes, into
the XML document, then the xpnStatus.Select never returns the Status nodes.
I've also tried xpnStatus.Select("descendant::Status",
"http:///www.mydomain.net/mynamespace")  and xpnStatus.Select("Status",
"http:///www.mydomain.net/mynamespace") to no avail.

Any thoughts?

Here is a snipet of the XML...
<?xml version="1.0" encoding="utf-8"?>
<document xmlns:MNS="http:///www.mydomain.net/mynamespace")>
    <MNS:Status guid="8f8ecffd-a692-493c-91d9-0074b74ca56b" damage="false"
reset="false" save="true" show="true">
  <MNS:Name>
            <MNS:Name>Status1</MNS:Name>
            <MNS:Alias>Bl</MNS:Alias>
        </MNS:Name>
  <MNS:Description><![CDATA[Random description.]]></MNS:Description>
 </MNS:Status>
 <MNS:Status guid="b7273a52-d346-472c-8506-166f94ca896e" damage="false"
reset="true" save="true" show="false">
  <MNS:Name>
            <MNS:Name>Status2</MNS:Name>
            <MNS:Alias>Cp</MNS:Alias>
        </MNS:Name>
  <MNS:Description><![CDATA[]]></SRD:Description>
 </SRD:Status>
</document>


0
7/19/2004 6:18:05 PM
dotnet.xml 7266 articles. 0 followers. Follow

1 Replies
897 Views

Similar Articles

[PageSpeed] 40

You have to populate an XmlNamespaceManager and pass it to the navigator
Select method.

"Hollywood" <hollywood@thzero.com> wrote in message
news:O1h2DzbbEHA.904@TK2MSFTNGP09.phx.gbl...
> I have the following code that is attempting to read nodes from an xml
> file...
>
> XmlDocument xpdStatus = new XmlDocument();
> xpdStatus.Load("status.xml");
> XPathNavigator xpnStatus = xpdStatus.CreateNavigator();
>
> XPathNodeIterator xpniStatus = xpnStatus.Select("descendant::Status");
> while (xpniStatus.MoveNext())
> {
> Console.WriteLine("Book title:  {0}", xpniStatus.Current.Value);
> XmlNode node = ((xpniStatus.Current) as IHasXmlNode).GetNode();
> Console.WriteLine("Status:  {0}", node.Value);
> }
>
> The code works fine until I attempt to add namespaces, with prefixes, into
> the XML document, then the xpnStatus.Select never returns the Status
nodes.
> I've also tried xpnStatus.Select("descendant::Status",
> "http:///www.mydomain.net/mynamespace")  and xpnStatus.Select("Status",
> "http:///www.mydomain.net/mynamespace") to no avail.
>
> Any thoughts?
>
> Here is a snipet of the XML...
> <?xml version="1.0" encoding="utf-8"?>
> <document xmlns:MNS="http:///www.mydomain.net/mynamespace")>
>     <MNS:Status guid="8f8ecffd-a692-493c-91d9-0074b74ca56b" damage="false"
> reset="false" save="true" show="true">
>   <MNS:Name>
>             <MNS:Name>Status1</MNS:Name>
>             <MNS:Alias>Bl</MNS:Alias>
>         </MNS:Name>
>   <MNS:Description><![CDATA[Random description.]]></MNS:Description>
>  </MNS:Status>
>  <MNS:Status guid="b7273a52-d346-472c-8506-166f94ca896e" damage="false"
> reset="true" save="true" show="false">
>   <MNS:Name>
>             <MNS:Name>Status2</MNS:Name>
>             <MNS:Alias>Cp</MNS:Alias>
>         </MNS:Name>
>   <MNS:Description><![CDATA[]]></SRD:Description>
>  </SRD:Status>
> </document>
>
>


0
clovett1 (13)
7/20/2004 2:53:06 AM
Reply:

Similar Artilces:

Conditional namespace
Hi Everyone, I want to include the namespace "using Windows7.DesktopIntegration" in my C# project only if the current OS is Windows 7, for other OS like Xp,2000,vista I need to ignore the same. Any idea for achieving this will helpful for me. -- Thanks and Regards, Shankar B. Shankar wrote: > Hi Everyone, > > I want to include the namespace "using Windows7.DesktopIntegration" in my C# > project only if the current OS is Windows 7, for other OS like Xp,2000,vista > I need to ignore the same. > I'm puzzled. AFAIK the only r...

Testing for non-existing namespace attribute?
Hello! I'm using msxml3 in the C++ environment, VC 7.1.3088. How do I know if the namespace attribute doesn't exist? I want to put it in a std::string, and I try to do that like this: string CXmlNodeWrapper::GetNamespaceURI() const { if( IsValid() ) { _bstr_t str = m_xmlnode->GetnamespaceURI(); return static_cast<char*>(str); // <- point of exception } return ""; } m_xmlnode is a MSXML2::IXMLDOMNodePtr; This works fine as long as there is a namespace attribute, but if the root node doesn't have a namespace attribute thi...

SelectSingleNode and Namespace
This is a multi-part message in MIME format. ------=_NextPart_000_0006_01C54429.49A1B710 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I use a XML-Doc with a Namespace like the following example: <HomedResources = xmlns=3Dhttp://schemas.microsoft.com/RtcServer/2002/11/dbimpexp = Version=3D"3"> <HomedResource UserAtHost=3D"PBoul@team.de" Enabled=3D"1" = VersionPermission=3D"10" =20 VersionContact=3D"25" DisplayName=3D"Boullay, Peter" = Email=3...

Serializing Class with Unqualified Root Element and Default Namespace attribute
I'm trying to serialize (using XmlSerializer.Serialize) a class that I generated from an XSD schema using XSD.EXE /c. The problem I'm running into is that the root element needs to be unqualified, and the default namespace needs to be included on it as an attribute. The schema I'm using is this: <xs:schema xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:xs="http://www...

XPathNavigation and Namespaces.
I have the following code that is attempting to read nodes from an xml file... XmlDocument xpdStatus = new XmlDocument(); xpdStatus.Load("status.xml"); XPathNavigator xpnStatus = xpdStatus.CreateNavigator(); XPathNodeIterator xpniStatus = xpnStatus.Select("descendant::Status"); while (xpniStatus.MoveNext()) { Console.WriteLine("Book title: {0}", xpniStatus.Current.Value); XmlNode node = ((xpniStatus.Current) as IHasXmlNode).GetNode(); Console.WriteLine("Status: {0}", node.Value); } The code works fine until I attempt to add namespaces, with prefixes...

Documents w/o namespaces
I've developed a web service whose output is an XML document that conforms to a schema. Is it bad practice / unacceptable not to have a namespace associated with my document? If so, is it OK to just supply a default namespace and thus negate the need for namespace prefixes on all elements? Lastly, is it OK to reference the URL of the .xsd schema document itself as the URI of the namespace? Brad Wood wrote: > I've developed a web service whose output is an XML document that > conforms to a schema. > > Is it bad practice / unacceptable not to have a namespace ass...

XPathNavigator
When I try this //WebSRFTemplate/Data/Field[Name='SERVICEStaticRoute2IPnetwork1']/text() I get back the values of ALL Fields in my XML below. I only want the value (Test1) of the field name specified. Am I doing something wrong here? <WebSRFTemplate Version="1" Type="SERVICE"> <Data> <Field Name="SERVICEStaticRoute2IPnetwork1">"Test1"</Field> <Field Name="SERVICEStaticRoute3Subnetmask">"Test2"</Field> <Field Name="SERVICEStaticRoute3IPnetwork1">"Test3"<...

Web Service returning class in XML with namespace information
Hi All, I am trying to return a class from a Webservice without having to deal with xmlns:xsd and xmlns:xsi. I have to get rid of those because this is sent over an expensive network and I'd like to minimize the cost. I've seen posts that show how to do this, but it didn't work for me. Here is what I've done so far: public class clsQueTrans { public string label; public byte[] data; } [WebMethod] public clsQueTrans GetNextMessage(string queueName) { clsQueTrans qt = new clsQueTrans(); qt.label = "fing"; qt.data = new byte[10]; for(int i = 0; i <...

My app fails when calling Outlook.Namespace.Folders
I made a program that reads emails from an Outlook mailbox and does some stuff and the program works fine. However, my boss now tells me that the program is to be executed from a remote computer. I now get the following error when calling the program remotely: "Could not complete the operation because the service provider does not support it. at Outlook.NameSpaceClass.get_Folders() For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp." Below is the piece of code in the program where the error occurs: ' Create Outlook application ...

How to insert a CDATA section using XPathNavigator ?
Can anybody show me how to insert a CDATA section using XPathNavigator ? I have tried the follwing with no luck: XmlDocument docNav = new XmlDocument(); docNav.LoadXml(xmlString); XPathNavigator nav = docNav.CreateNavigator(); XmlDocument doc = new XmlDocument(); doc.LoadXml("<DocumentData></DocumentData>"); XmlElement elem = doc.CreateElement(currentNodeName); elem.AppendChild(doc.CreateCDataSection(dataString)); doc.DocumentElement.AppendChild(elem); XPathNavigator newNav = doc.CreateNavigator(); nav.InsertAfter(newNav); Regard...

XPathNavigator and name()
Hi; Two questions. I have an XPathNavigator object where it's OuterXml property is "<jan>231</jan>" and I am trying to write an xpath statement that will return the "jan". XPathNavigator nav = ...; 1) I can do nav.Evaluate("name(parent::*)"); and get "month". But if I do nav.Evaluate("name(self::*)"); I get "" returned. Shouldn't I get "jan"? 2) This is for code that can be passed random xpath statements. For some it seems I need to call nav.SelectSingleNode(xpath) and for some (the name() exampl...

Implementing XPathNavigator on my class
Hi, I've an 'Employee' class. In my program this object is manipulated, children (List<T>) added, properties modified etc. Everytime this happens I want to be able to show some relevent html to the user. So I use XSLTransform. This Employee class is basically an XML serializable class produced out of an XML file when the program loads for the first time. Later on, if I've to show the modifications done to this object, I don't want to go back to save this object into the file, then load it to XMLdocument object and then use XSLTransform on it. This is tedious, nasty a...

Namespace issues.
We have a XML script which uses the default namespace. See below: <?xml version="1.0" encoding="UTF-16"?> <Import xmlns="http://www.blah.com/nVanta" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blah.com/BlahBlah.xsd"> .... Then we try to read the nodes from the XML file using following code ( simplified for clarity) : public IXmlMapperNavigator Read(string xPath ) { XmlMapperNavigator map = null; // Optimize the ...

XPathNavigator.getUniquePath()
Hi; Is there a way from an XPathNavigator object to get an xpath string that will, when used in a Select(xpath) on the underlying base/root XPathNavigator return the same XPathNavigator? In other words, I initially create an XPathNavigator for my entire xml document. To get an XPathNavigator object who's root is a given node in the original xml document, there is a unique xpath that will return that node. The unique xpath could have, as an example, [2] in it depending on which node in a list of identical nodes, this one is. I may do a Select on a Select on a Select and have an XPa...

XmlSerializerNamespaces moves namespace to root node
This problem should be easily reproducable if anybody has the time. I need to build the following XML programatically and decided to use the XMLSerializer. I simplified the XML (myExample.xml) that i need to create for this post. <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <m:TopElm xmlns:m="myNameSpace"> <Elm1>H...

assign dt as namespace for xmlelement
I am trying to duplicate an xml document, and I am pretty new to xml. I am using hte Xml namespace and taking advantage of the xmldocument class. I would like to add the following to an element xmlns:dt="urn:schemas-microsoft-com:datatypes" Is there a way to do this through the setattribute or createelement methods? Whenever I try all i get is the xmlns="urn:schemas-microsoft-com:datatypes" -------------------------------- From: Matt Torline ----------------------- Posted by a user from .NET 247 (http://www.dotnet247.com/) <Id>X8iAJQuYZEulcatGDsqe+w==</Id&...

Namespace Question
I sent this question in before, so apologies. I have a number of schemas which I add into a schema collection. A number of the schemas define types, the others contain business context message details (e.g. updating an employee etc). The schemas which define general types have their own namespace defined. All the other schemas have the >>same<< namespace. After loading 101 schemas into my collection I get the error "Server was unable to process request. The global element urn:xxxx/yyy/zzz:abc has already been declared" There are still approximately 140 schemas in tota...

SelectSingleNode with namespaces
My question is somewhat related to the previous question in this newsgroup: http://groups.google.de/group/microsoft.public.dotnet.xml/browse_frm/thread/db094f140f8359ca/5d58771b3b60cd47?hl=de#5d58771b3b60cd47 I am having trouble unerstanding how to use XmlNode.SelectSingleNode Method (String, XmlNamespaceManager) node when an xmlns Atrribute is present. this is my xml file: <?xml version="1.0" encoding="utf-8" ?> <configuration xmlns="http://company.de/VCT9/Core/Configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quo...

xmlns:g
I found some sample code to construct an rss feed and am trying to modify it to match Google's specs at: http://www.google.com/base/rss_specs.html, but without knowing much about XML. Their samples show the namespace declaration in the rss tag, I tried it both ways with the same result. It seems reasonably clear, add a namespace: XmlElement docNode = rssDoc.CreateElement("rss"); XmlAttribute attr = rssDoc.CreateAttribute("version"); attr.Value = "2.0"; docNode.Attributes.Append(attr); XmlAttribute attr1 = rssDoc....

Getting nodes with or without namespaces.
Hello, I'm having trouble trying to write a generic solution for parsing xml files. The xml-files I recieve can have namespaces or not, depending on the source - however, the treestructure is the same for all. An extra difficulty is that it is not certain that if a xml-file has namespaces, all nodes will use the namespaceprefix: some will and some will not. Adding namespaces to the namespacemanager is no problem. How do I know if a certain node uses a namespace prefix? Is there a property I can check? thanks, ru ru wrote: > How do I know if a certain node uses a namespace p...

XPathNavigator.ValueAsBoolean
Hi; How can I tell if I can call XPathNavigator.ValueAsBoolean safely - without throwing an exception. I want to take one course of action if the value can be interpreted as a boolean. But I din't want to do it using try/catch - I think having exceptions be thrown when the code is operating normally is very bad - both from a performance point of view and because it signifiys an error. -- thanks - dave Hi dave, Currently we are looking for someone to help you on this issue, we will reply to you ASAP. Thanks for your understanding. Best regards, Jeffrey Tan Microsoft Online Partn...

Namespace headache
I'm using the following XML: ----------------------------------------------------------------------------------------- <?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Url="_catalogs/masterpage" Path="PageLayouts" RootWebOnly="TRUE"> <File Url="List.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE"> </Module> </Elements> ------------------------------------------------------------------------...

Programming without XPathNavigator.SelectSingleNode (framework 1.1)
Hi, given the following simple XML fragment: <country> <code>ES</code> <description>SPAIN</description> <destination> <code>IBZ</code> <description>IBIZA</description> </destination> <destination> <code>PMI</code> <description>MALLORCA</description> </destination> <destination> <code>MAH</code> <description>MENORCA</description> </destination> </country> <country> <code>PT</code> <description>PORTUGAL</...

XPathNavigator Question
Hi My function receives an XPathNavigator object. From here I need to build a DataSet to load into SQL Server (using SQLXML adaptor). Does anyone have an idea on the most efficient way to convert the XPathNavigator into a DataSet? Here is what I have at the moment: void function DoSomething( string xmlSchemeFile, System.Xml.XPath.XPathNavigator nav ) { System.Xml.Xsl.XslTransform transform = new System.Xml.Xsl.XslTransform(); System.IO.Stream stream = System.IO.MemoryStream(); transform.Transform(nav, null, stream); // Create the dataset based on the schema, then read in ...

XPathNavigator compile
Hi, Is the compilation of XSLT, using XPathNavigator.Compile, only beneficial when the returned XPathExpression is cached? Next question, how do I cache the returned XPathExpression object? Should I programmatically cache it or is it automatically cached when the Compile method is called? Thanks Richard. news.microsoft.com wrote: > Is the compilation of XSLT, using XPathNavigator.Compile, only beneficial > when the returned XPathExpression is cached? You probably meant XPath, not XSLT. In fact, XPath expressions are always compiled internally before evaluation. XPathNavigator....