Xml // Reading Element Value // Namespace issue // XPathExpression XmlNamespaceManager

Ok, my xml inability shows itself once again.


Thanks for any help.




Below I have some xml and some code for trying to get the "Publish_Date" 
element value.


I've tried 4 different ways to get it.
(If you uncomment the lines in the code seen here, you can see the ways I've 
tried to get the value)
theOneImGonnaTry = myNameSpaceNameLocalName1 + ":";
theOneImGonnaTry = myNameSpaceNameLocalName2 + ":";
theOneImGonnaTry = myNameSpaceNameLocalName3 + ":";
theOneImGonnaTry = string.Empty;

(The code seen above makes more sense when you look at the code below).


Below is the xml sample (and its source url in the code) and the C# code I'm 
trying to use.



---------START XML
<?xml version="1.0" standalone="yes"?>

<sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://tempuri.org/sdnList.xsd">

<publshInformation>

<Publish_Date>02/10/2010</Publish_Date>

<Record_Count>4301</Record_Count>

</publshInformation>

</sdnList>



---------END XML



C# code below





string sdnUrl = 
"http://www.ustreas.gov/offices/enforcement/ofac/sdn/sdn.xml?fakeParameter=" 
+ DateTime.Now.ToLongTimeString();

XPathDocument doc = new XPathDocument(sdnUrl);

XPathNavigator nav = doc.CreateNavigator();





string myNameSpaceNameLocalName1 = "xsi";

string myNameSpaceNameLocalName2 = "myxsi";

string myNameSpaceNameLocalName3 = "anythingHere";

string theOneImGonnaTry = string.Empty;

theOneImGonnaTry = myNameSpaceNameLocalName1 + ":";

//theOneImGonnaTry = myNameSpaceNameLocalName2 + ":";

//theOneImGonnaTry = myNameSpaceNameLocalName3 + ":";

//theOneImGonnaTry = string.Empty;

string myXPath = "//" + theOneImGonnaTry + 
"sdnList/publshInformation/Publish_Date";

Console.WriteLine("Let's try : " + myXPath);

XPathExpression xpExpress = nav.Compile(myXPath);

XmlNamespaceManager context = new XmlNamespaceManager(nav.NameTable);

context.AddNamespace(myNameSpaceNameLocalName1, 
"http://www.w3.org/2001/XMLSchema-instance");

context.AddNamespace(myNameSpaceNameLocalName2, 
"http://www.w3.org/2001/XMLSchema-instance");

context.AddNamespace(myNameSpaceNameLocalName3, 
"http://tempuri.org/sdnList.xsd");

xpExpress.SetContext(context);

XPathNodeIterator nit = nav.Select(xpExpress);

while (nit.MoveNext())

{

XPathNavigator nav1 = nit.Current.Clone();

Console.WriteLine("Publish_Date: " + nav1.Value);

}












0
sloan5710 (6)
2/22/2010 4:27:51 PM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
1127 Views

Similar Articles

[PageSpeed] 16

sloan wrote:

> <?xml version="1.0" standalone="yes"?>
> 
> <sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
> xmlns="http://tempuri.org/sdnList.xsd">
> 
> <publshInformation>
> 
> <Publish_Date>02/10/2010</Publish_Date>
> 
> <Record_Count>4301</Record_Count>
> 
> </publshInformation>
> 
> </sdnList>

The following should suffice:

             XPathDocument doc = new XPathDocument("input.xml");
             XPathNavigator nav = doc.CreateNavigator();
             XmlNamespaceManager mgr = new 
XmlNamespaceManager(nav.NameTable);
             mgr.AddNamespace("df", nav.SelectSingleNode("*").NamespaceURI);
             Console.WriteLine(nav.SelectSingleNode("//df:Publish_Date", 
mgr).Value);


Or use LINQ to XML:

             XElement root = XElement.Load(@"..\..\XMLFile1.xml");
             XNamespace df = root.Name.Namespace;
             Console.WriteLine(root.Descendants(df + 
"Publish_Date").First().Value);

-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1778)
2/22/2010 4:45:20 PM
Thanks (again!) Martin.



"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:urt0t59sKHA.4796@TK2MSFTNGP02.phx.gbl...
> sloan wrote:
>
>> <?xml version="1.0" standalone="yes"?>
>>
>> <sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
>> xmlns="http://tempuri.org/sdnList.xsd">
>>
>> <publshInformation>
>>
>> <Publish_Date>02/10/2010</Publish_Date>
>>
>> <Record_Count>4301</Record_Count>
>>
>> </publshInformation>
>>
>> </sdnList>
>
> The following should suffice:
>
>             XPathDocument doc = new XPathDocument("input.xml");
>             XPathNavigator nav = doc.CreateNavigator();
>             XmlNamespaceManager mgr = new 
> XmlNamespaceManager(nav.NameTable);
>             mgr.AddNamespace("df", 
> nav.SelectSingleNode("*").NamespaceURI);
>             Console.WriteLine(nav.SelectSingleNode("//df:Publish_Date", 
> mgr).Value);
>
>
> Or use LINQ to XML:
>
>             XElement root = XElement.Load(@"..\..\XMLFile1.xml");
>             XNamespace df = root.Name.Namespace;
>             Console.WriteLine(root.Descendants(df + 
> "Publish_Date").First().Value);
>
> -- 
>
> Martin Honnen --- MVP XML
> http://msmvps.com/blogs/martin_honnen/ 


0
sloan5710 (6)
2/22/2010 5:00:34 PM
Reply:

Similar Artilces:

XML Header
Hi, I have some XML doc loaded in a C# Web Service. XmlDocument doc = new XmlDocument(); doc.LoadXml(myDoc); Code Missing to manipulate header (I would like to replace or manupulate all these XXXXX): <mso-XXXXXX productversion="XXXXXX"> <mso-application progid="XXXXX"?> doc.Save(myNewDoc); Any idea on how to access and manipulate data within the doc header? Thanks vbdev vb6dev2003 wrote: > I have some XML doc loaded in a C# Web Service. > XmlDocument doc = new XmlDocument(); > doc.LoadXml(myDoc); > > Code Missing to manipulate header ...

Read XHTML into XML
Hi all, I need to read/parse XHTML aspx pages and look for certain tokens and content. How can I use a XmlTextReader for this? If not, any other ideas? Thanks in advance, JA Reyes. Jose Antonio Reyes wrote: > I need to read/parse XHTML aspx pages and look for certain tokens and > content. How can I use a XmlTextReader for this? If not, any other ideas? If the pages are well-formed XHTML then it is possible to use XmlReader (in .NET 2.0/3.0) or XmlTextReader (in .NET 1.x) to parse the XHTML documents. You can also use the other XML APIs .NET provides so using XPathNavigator and/o...

How to invoke the xml editor?
I installed vs2005 on a new xp pro machine, and installed everything except C++. When I click on a file with a ".xml" extension it is opened with IE. When I click file/Edit with XML Editor, it opens it with Notepad. If I click File/Open With and select XML Editor, it opens it with IE. So, where is the xml editor? Can it be invoked from withing VS? Where? Bill * billsahiker@yahoo.com wrote in microsoft.public.dotnet.xml: >I installed vs2005 on a new xp pro machine, and installed everything >except C++. When I click on a file with a ".xml" extension it is >opened ...

VB Assigning Values to a Series of Strings
Hello, In the VB Editor, I need to assign each letter of a 13 character string (named JobScope) to individual Variables (K1 through K13). I'm using a For/Next Loop to extract the indiv characters but cannot figure out how to define the Variable K(x) where x = 1 to 13. Any suggestions? -- Regards... cincode5, Try making K an array with 14 elements (VBA numbers the first element as 0) Then you can use the method you're trying at the moment. For X = 1 To 13 K(X) = etc. ~ ~ Next X The only other change you'll have to make is how you address the variables elsewhere. E.g, K5 w...

show XML schema and values
I have an XML document that looks like the following: <record> <Field1>value1</Field1> <Field2>value2</Field2> <Field3>value3</Field3> </record> What I'm aiming to do is to show the data in a report as in the following example: record: Field1 value1 Field2 value2 Field3 value3 The "Field1-3"-elements can have any name, so I'm trying to get a table that has in one result column the element name, and in the second colum...

Moving a line chart data point revises data table value in Excel '
I recall a capability I used with Excel years ago that enabled me to create a line chart from a data table, then move the plot points on the chart to "smooth" the line, and the source data chart value would change with the corresponding new plotted point. I'd like to use that capability with Excel 2007 but can't find to activate it. Any power users know how? Thanks! Ed Ed, Microsoft decided that users didn't need that feature. More than likely, they were tired of support calls asking why the values changed when one dragged a data point...... No really, they took i...

Offline synch using XML web-services
This is a bit long-winded. Can somebody read thru these 2 use cases, and tell me if it is feasible ? :- Use Case : Replication before Offline Synch Scenario 1 : Oracle Server , MSDE client 1. User clicks on 'Go Offline'. System creates a MSDE SQL database in laptop (client), gets the schemas of the tables in Oracle, creates corresponding tables in client's MSDE SQL (mapping Oracle datatypes to SQL datatypes). 2. Offline replication program reads in the tables of the server into a typed datasets, converts the typed datasets into XML, and stores the XML in the client. (XML serial...

XML Serialization ... how to truncate <?xml...
While xml serializing object how can I truncate <?xml ...?> this line alone? I need to send the serialized xml data to a web method ... since SOAP already have <?xml tag there was some confusion Any help would be greatly appreciated Thank you Regards Raj Raj wrote: > While xml serializing object how can I truncate <?xml ...?> this line alone? Serialize to an XmlWriter created with XmlWriterSettings where you set OmitXmlDeclaration to true. -- Martin Honnen --- MVP XML http://msmvps.com/blogs/martin_honnen/ ...

how do I change "read only" to copy files onto a Cd-RW
I copied files onto a Memorex CD-RW with no problems. I had a major crash and reloaded Windows 98 and was able to retrieve the files, but now when I want to save files, with new changes on the CD-RW it says "read only". I've looked into Properties and haven't any success. It is not a good idea to read and write files to removable media. Copy the file to your hard drive from Windows Explorer, save back to the hard drive and copy to the CD-RW from Windows Explorer. If you need to remove the read-only attribute, you can do that from Explorer, too. On Mon, 8 Nov 2004 18:0...

String to xml document
Hi there, I was hoping someone can help me with a little problem I can't seem to find any answers to. I've got a form wich will be posted. On receiving the post I would like to parse a formvar to a xml document. The contents of this formvar (string) will be a valid xhtml document. Can someone give me a startertip (or more :-)) on how to achieve this? tnx in advance, James van der Veen Sjeems wrote: > I was hoping someone can help me with a little problem I can't seem to find > any answers to. > > I've got a form wich will be posted. On receiving the p...

Threads which just read data
Hi, I have many threads in my program. I would like to know if it is safe to allow the threads access to a variable to just read its contents, without having a synchronizing object ? Could there be problems like memory corruption etc if I allow it ? I don't see any reason why it will be unsafe to allow threads to just read contents, without having a synchronizing object. Please correct me if I'm wrong. Thanks, -Venkatesan On Sat, 25 Oct 2003 19:03:19 +0530, "Vengidi" <vengidi@yahoo.com> wrote: >Hi, > I have many threads in my program. I would like to know i...

Beginner of XML
I am a beginner of XML. I want to group some files together with a xml file. (it includes a text file, and an image file and a video file) Can someone show me some guidelines? Please help. ...

Valid xml to read from an xml file?
I'm using vb.net, i get an error at the reader line saying the remote server can't be found. Is the below even valid? dim reader as XmlTextReader reader = new XmlTextReader ("http://www.mysite.com/my.xml") do while (reader.Read()) 'do some action here response.write(reader) loop thanx chumley XmlTextReader uses System.Net.WebRequest under the covers -- see if you can figure out how to create a connection that way. Usually there's some proxy server information missing that you can enable if you use WebRequest directly, and then pass the result of GetResponse()...

Example eConnect XML documents
MSDN says the following: Installing eConnect schema When you include the schemas component of the eConnect install, the installer places schema files in a schemas folder on your computer. The following schema resources are available: The install places the .xsd schema files in the directory c:\Program Files\Microsoft Great Plains\eConnect9\XML Schema\Incoming XSD Individual Schemas. The files in the directory contain the schema for each eConnect XML document. The install places a file named eConnect.xsd that contains the schema definition for all eConnect XML documents. The install typicall...

Registry Security Issue
Client has locked down users. The normal users cannot get into SO. They are getting this message "Your Windows account does not allow you to write to the registry" What minimum rights must I give them? All Admin users can run RMS just fine. Rich, This is a common problem. RMS was built a number of years ago before the security push. Most of the information is stored in the registry, so the user needs to be able to read and write to the HKLM\SOFTWARE\Microsoft\Retail Management System\Store Operations key. Its easier just to give them full access to this key instead of try...

Typed in value changes? #2
Hi Folks , I am sure that I must have done something screwy and changed some options around but I have not been able to figure out what the problem is. The issue is that whenever I type a value into a cell it automatically divides that number by 100 and that is the value that is then displayed in the cell (ie typing 3 into the cell results in 0.03 being displayed). This just happened all of a sudden and it does not matter if I am in a file I previously created or a new file and it does not matter what column or row I type the value in. It is worth noting that if I open up previously...

Previous value
Hi there, In a detail section, is there a way to get the previous field value in the previous record? I'm asking this because each current is calculated with the previous value. The first a simple calculation based on current values. looks like recursive code, but how to do without vba? Thanks in advance for any good suggestion I can't tell from your description how you (and therefore, how Access) determines "previous". You'll need to be able to define that in a way that you can explain to Access. If you are trying to build a "running sum...

Saving DataSet as XML in ADO format using VB.NET
Hi, I am trying to convert a lot of web reports from ASP/VB to ASP.NET/VB.NET. I would like to save my dataset in XML and then use XSLT to transform the XML. The catch is I would like to have the XML in the format that ADO uses versus the default format in which ADO.NET uses. Currently, I am using ADO within .NET, but I am concerned about the performance and it might improve if I used the native data providers for .NET. I am not sure if I am missing something but how do I save the .NET DataSet to XML in the OLD ADO format? Thanks for you help in advance and it is most appreciated. In the ...

eConnect RMALine null value error
Hi, Everyone: I am working on a eConnect RMA project. When I sent the eConnect RMA XML file to the backoffice by calling: eConnProxy.eConnect_EntryPoint(Components.Globals.eConnectConnectionString, EnumTypes.ConnectionStringType.SqlClient, XmlCustomer, EnumTypes.SchemaValidationType.None, "") I got the following exception: Microsoft.GreatPlains.eConnect.eConnectException: Sql procedure error codes returned: Error Number = 9911 Stored Procedure taFSRMALine Error Description = At least one input variable contains a null value This is my xml file: <FSRMAType><eConn...

linking to external file based on cell value
Hello folks, I am wondering if it is possible to set up a link within excel that references an external file using a cell value in the main spreadsheet. For example: this is the current setup =[expense_allocation.xls]Jan04!$G$5 instead of the Jan04 in the link, I would like a cell reference I tried this but it does not seem to work: ="[expense_allocation.xls]" & A1 & "!$G$5" where A1 = Jan04 Any ideas would be appreciated. Thanks, Jason Hi Jason, Instead of typing it in, open up both files and select each cell as you're creating the formula to make...

XML variable for description on receipt?
Hi, I would like to add a description (actually all of those 3 extended descriptions) to display on the printed receipt under the main description. What is the variable to do that? Entry.Item.Description Entry.Item.ExtendedDescription Entry.Item.SubDescription1 Entry.Item.SubDescription2 Entry.Item.SubDescription3 R. "Zorian" <Zorian@discussions.microsoft.com> wrote in message news:F4425EAC-62B6-46FE-826A-D8BA2AA75DBB@microsoft.com... > Hi, I would like to add a description (actually all of those 3 extended > descriptions) to display on the printed receipt un...

i enter value in one column the next column existing value turn 0
I am working same work sheet with two columns one is Anticipated Variation cost and the other approved variation with corresponding total. when i enter cost in approved variation the corresponding row in anticipated variation column should auotmaticlly become zero.cna you help me out with the formula to use =IF(A1<>"",0,"") -- Regards Dave Hawley www.ozgrid.com "Bonnie" <Bonnie@discussions.microsoft.com> wrote in message news:1F5A64A0-224E-4C75-84A9-BC7DCABD52F7@microsoft.com... >I am working same work sheet with two columns o...

currency issue with eConnect
I wrote a web service that passes Xml to the eConnect_API to insert an invoice into Great Plains eEnterprise 7.0. Working against the World Online database, the web service is working. When I switched to production, the invoice could no longer be entered; I get this error from eConnect: "Invalid Currency, a Functional currency must be set up" Looking around in production, it looks like there are no currencies set up. Is that possible? Any insights would be appreciated. Thanks -Tom Hartnett ...

xml to SQL
Hey we have a project in which a company produces a XML page in reply to actions on it's site. I see that SQL 2000 works well with XML so Can someone point me in the right direction, I would like to take the XML from thier SQL and have it "post" to own sql server (add,create, data, modifity and delete data on the fly). I was looking at doing XML to HTML and then passing to some a ASP but if we can grab from the responsetext then we could save time and headaches. Now I really know next to nothing about XML but I am reading all the newsgroups and pulled now TONS of xml / sql stuff ...

Want to make excel to pull up a jpeg based on cell values
I want excel to pull up a jpeg based on a cell's value. It would inser the jpeg into another cell. An example: If A:25 has a value of 5 can exel grab 5.jpeg fro somewhere and insert it into another cell, say C:25? I assume the best place to put these jpegs for excel's use is o another worksheet -- fishbi ----------------------------------------------------------------------- fishbin's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2072 View this thread: http://www.excelforum.com/showthread.php?threadid=49195 Perhaps you can adapt this: http://ww...