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
2539 Views

Similar Articles

[PageSpeed] 13

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 (1777)
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:

Deserialize an XML file with multiple namespaces...
Hopefully I can ask this question without regaling you kind people in too many gory details. Here's what I'm trying to do: - I have a local XML file with a .GPX extension which I downloaded from www.geocaching.com. - The file contains a bunch of elements called <WPT> - Within the WPT elements are a number of other elements <time>, <sym>, <groundspeak:name>... - The non-qualified elements come from a schema/namespace at http://www.topografix.com/GPX/ - The qualified elements come from a schema/namespace at http://www.groundspeak.com/cache - I ran xsd.exe with th...

CRM 4.0 queue issue
Hi, I've run into this in CRM 3.0 (and honestly, I don't know what I did to fix it). But now it's happening in CRM 4.0. I have a queue, and a user with an email address. I want all email that is sent to this user to also appear in the CRM queue. I have it working, it's just that I'm getting everything twice. Once as an email from the original sender, and once from the recipient to the recipient, with the original email as an attachment. For example, kbriscoe@domain.com sends an email to ITSupport@domain.com (Our queue's email address is ITSupport@domain.com). T...

EMail Read-receipts
Hi, Can we have email read-receipt functionality please. We use quick campaigns to send out questionnaires but do need a read-receipt to indicate that the email has been seen. -- Pete ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Business...

Preventing [Read Only]
Is it possible to stop people opening a workbook in read only format? I have a document which when used, prints individually numbered labels, and saves the information in an archive. Instances have occurred where reference has been made to a certain label number, bu it relates to different information than what he archive says. All because somebocy produced the label in read only mode, therefore not saving the information in the archive. Saved from a previous post. How about closing the workbook if it's opened readonly--and this'll only work if macros are enabled! Option Explic...

Access Code Pushing Values
I have a customer database with [BillAddress] and [ShipAddress]. I am using a "yes/no" box titled[SameShipAddress?]. To automatically fill [ShipAddress] after checking the "yes/no" box I used this code in the after update event for the check box. If Me![SameShipAddress?] Then If IsNull(Me![BillAddress]) Then Else [ShipAddress] = [BillAddress] End If End If This works for the selected customer, but then pushes the entry [BillAddress] of the previous customer to [ShipAddress] of all of the following customers. Any thoughts? Sounds as...

enter value based on drop down list of another field?
I have an excel 2003 spreadsheet with 3 worksheets. In sheet 1, I created a drop down list in column A based on values in sheet 3, column A (item number). Thisd data comes from sheet 3, where I have column A (Item #'s), column B (Item desc)an Column C (price) In column B of sheet 1, I have Item Descriptions and in column C I have price. I want this to automatically fill in based on what I enter in the column A sheet 1 and it should get the corresponding values from sheet 3 column B and C. I can make the drop down list in sheet 1 column B and C, but some of the descriptions need ...

create xml document based from schema
I have the following schema. I need to know how to make an xml document based from it. The main worry I have is the DateTime field. <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="NewsArticle"> <xs:complexType> <xs:sequence> <xs:element name="Description" type="xs:string" /> <xs:element name="Body" type="xs:string" />...

Xml-Grid for editing NodeList
Hey XML-Guys, I'm playing now for a couple of days with C# and XML. In earlier threads a mentioned that I develop smaller Web-Applications. Therefore I want to edit and add new nodes to my Xml-Documents. To use a DataSet is not very handy because if the data is to complex it allowed me not to add a row. I'm looking for a XML-Grid that is able to have a XML-File as DataSource and let me filter the Data over a XPath-Expression. After filtering a want edit the resulting NodeList and also add Nodes. The Header of the Grid should show the NodeNames and the DataRows should conta...

Retreiving Xml child nodes using DataSet and XmlDataDocument
I am loading an Xml file from a sql server. I have one field that contains child nodes stored as text. The problem is, when I try to imort the dataset into a XmlDataDocument, it loads the whole thing as a text element. (with all of the special characters converted) The best solution I've found so far is to do a string replace on all of the special characters. Like so: DataSet ds = new DataSet(); ds.EnforceConstraints = false; SqlDataAdapter da = new SqlDataAdapter(query, connStr); da.Fill(ds, "Keywords"); XmlDataDocument xmlDoc = new XmlDataDocument(ds); string s = xmlDoc.S...

How do I filter rows based upon a column value
I have a spreadsheet that contains multiple agency id's in a column. When generating reports, I would like to filter per agency and display only the rows associated with that agency. Is there a tutorial or sample on how to do this? Hi It sounds like you are looking for Data / Filter / AutoFilter. Have a look here for some basics: http://www.contextures.com/xlautofilter01.html -- Andy. "Jack" <nfr@nospam.com> wrote in message news:eqiU08TVEHA.2988@TK2MSFTNGP10.phx.gbl... > I have a spreadsheet that contains multiple agency id's in a column. When > generati...

text size in reading pane
Where is the font selection / text size control for the Outlook 2003 reading pane (incoming emails)? I just bought a brand new dell with windows xp and all and I can't even increase the text size of incoming emails as I could with older versions of Outlook Express. I have been trying to figure this out for around 15 hours now and have come up empty. What kind of progress is this anyway???? A program rendered unable to accomplish such a simple practical thing like that!! Im very upset. My vision is poor. Unless I get an answer soon, I am considering a return of this unit to dell...

Major instal issue
I have Money 2002 installed, and have had for some time. About two weeks ago, I started getting the Windows Installer "preparing to install" message repeatedly when I open Money, or when the Money Viewer is invoked in IE. Both Money and the viewer work fine, but no matter if I cancel or ignore the message, it keeps coming up roughly once every two seconds. The real issue though is this: since this started happening, I've been unable to install or uninstall anything else that uses the Windows installer (including trying to uninstall Money to solve the issue), as it fails saying t...

Import custom namespace in XSLT
Hi, I wanted to use the <msxsl:script> tag in a XSLT and include a .Net defined namespace. For ex: System.Web It seems the framework 1.1 does not work in a manner mentioned in the documentation. The framework gives me a run-time exception and does not transform the input file Have you come across such situations and were able to implement the same? Any help would be appreciated. Thanks, Alok Alok Sathaye wrote: > I wanted to use the <msxsl:script> tag in a XSLT and include a .Net defined > namespace. For ex: System.Web Then when declaring and/or using object...

Great Plains 8.0 Evaluation CD
I have downloaded the CD using my MSDN subscription to evaluavate the product. But I am not able to read any documentation (neither PDF nor .CHM) files. Its giving me errors. I tried using both Acrobat 6.0 and 5.0 . Acrobat says files may be corrupted and when I tried opening .CHM files its says cannot open the file mk:@MSITstore: <file path> Any idea ? Please advise. Sakeer ...

Comparing cell values then labeling them based on comparision
Hi. I'm trying to find a function or way to compare two cells and then label them according to if one cell is lesser, greater, or the same as the other. I have a large data sheet where I want to compare many pairs of cells and then have them labeled in this way. For example for each pair where the second cell value is larger than the first it would put greater, where the first is larger it would be lesser, etc. Can anybody help me with this? also feel free to email me at andrew@metiri.com. Thanks so much for your help. > Hi. I'm trying to find a function or way to compar...

Migrating from Novell to Windows 2000 server causes issues with .PST on Win95/98
All: Hopefully someone has seen this before and can provide a clue. We are currently migrating all of our user home directories from Novell 5 servers to Windows 2000 servers. The majority of our clients are XP and Windows 2000 workstations using Outlook 2000. However, there are still a number of clients using Windows 95/98 and Outlook 98. After copying .PST files from the Novell home directory to the Windows 2000 home directory using a Windows XP workstation, users using the Windows 95/98 workstations get an 'access denied error' when attempting to open their .PST folder from the ...

Sum of values in a form
Folks, I have read numerous threads on this topic, and understand that in order for my Sum() to work I need t ensure all references are made back to the Record Source. I have endeavoured to do this, but am still getting #Error. I am trying to Sum the revenue each tenant provides in a given date range, to give a total revenue figure. If the date range is a whole month, then the expression just takes the value of Rent PCM, and not Rent PCM * No. of Days, which would give some unusual results. My Expression looks like this: =Sum(Nz(IIf([Short Let]=-1,[Rent pcm],IIf(Day([Forms]...

Combo box default value multiautocomplete
Hi All i have a subform with 10 item. The first one is a combo box that can choose the value from a list that is linked to a table with many record. This subform is related to the master form with link master field codice,cognome,nome link child field codice,cognome,nome that are the other items that are not visualize in the subform. These link give me the right connection to the master form. Normally when i choose the value from list (table) i place also all the other item in the subform using this code in after update precedure Me.ISEE.Value = Me.ISEE.Column(0) Me.F_Costo_con_M...

Add cell value with mouse click
I want to create a counter, so that every time I click in a certain cell it takes the existing number and adds "1" to it. Is there any way to do this? I'm compiling statistical information, and need to get cumulative counts in various categories as I sort through the data. Hi! Maybe you can use a spinner button for this. Right click any toolbar then select Forms. Click on the spinner button ( it looks like an up arrow on top of a down arrow). Place it near the cell you want increment. Once you have it placed and sized right click on it and select Format Control. Fill in ...

Weird Vista screen issues
Hey, my screen is really weird. My screen is both used for my computer and for my Xbox 360. Now, today when I switched the screen cable from the Xbox to my PC my screen is really weird. Firstly, I cannot seem to choose 1680x1050 as a screen resolution, as whenever I choose it it says it has changed but there's still weird screen stuff with it. Icons and text on my computer are much more unsmooth and it's really starting to annoy my eyes. What's up with mah scr33nz? -- Tomatketchup Tomatketchup wrote: > Hey, my screen is really weird. My screen is both us...

IIF Query for Numeric Values in Text Field
I’m attempting to flag interest rate spread errors and omissions in a file from a sales database using IIF statements I adapted from another database (I’m a novice at this). The field I’m querying is text format and contains both alpha and numeric values. When I test for a null value the IIF works fine, but when I test for a numeric value I get an #ERROR. Spread Error1: IIf(([Tbl 1 Eligible Closed Deposit Opps Appended]!Spread Is Null),1,0) Spread Error2: IIf(([CCC Fall 2007 Eligible Products]![IB/NIB]="NIB" And [Tbl 1 Eligible Closed Deposit Opps Appended]!Spread<4),1,0...

How to get task manager CPU and default memory column values
I need to return CPU and memory columns for each process in server from web service like task manager shows by default. I tried code below but s.TotalProcessorTime throws Win32exception with stack below. How to get CPU and real memory size from server using web service ? Andrus. static void Processes(StringBuilder sb) { List<Process> processes = new List<Process>(); foreach (Process process in Process.GetProcesses()) processes.Add(process); processes.Sort((a, b) => { ...

xml element names...
hi all, xml element names doesn't support names with whitespaces or symbol characters etc,... but is there any .NET class that can help convert these characters like hex form.... that is what XmlSchema does. Would hate to have to find these characters one at a time... thanks, System.Convert ? Or just do foreach(char Ch in ForbiddenChars) ClassName = ClassName.Replace(Ch,((int)Ch).ToString("X"));//You may have to cast the Ch to string, though that will convert a char to hex. "Maersa" <ma_ersa@hotmail.com> wrote in message news:eoScxcKwDHA.3428@TK2MSFTNGP11.ph...

Linking Values in Worksheets
Is there a simple method of linking a column of values in one worksheet to another worksheet? I can do it manually, one at a time but is there a way of copying the link down the column? (The columns are identical in length) Registers\[Stock Control-Sigma-SMTech.xls]Sheet1'!$C$1369 Registers\[Stock Control-Sigma-SMTech.xls]Sheet1'!$C$1370 Registers\[Stock Control-Sigma-SMTech.xls]Sheet1'!$C$1371 etc, etc Many thanks david Hi David try ='C:\Registers\[Stock Control-Sigma-SMTech.xls]Sheet1'!$C1369 and copy down Frank DavidM wrote: > Is there a simple method of linki...

most often occurent value(s)
I would like to count and determine the most often (10) occurent values (strings) in a column. How can I do that? Thank you very much your help. Tamas, Use a helper column of formulas. For example, in cell B2: =IF(COUNTIF($A$1:A2,A2)=1,COUNTIF(A:A,A2),"") Copy down to match your column, then use Data / Filter.. Autofilter and pick "Top 10" from the dropdown at the top of column B. HTH, Bernie MS Excel MVP "Tamas Konczer" <tamas.konczer@gmail.com> wrote in message news:1173871962.218348.123590@p15g2000hsd.googlegroups.com... >I would like ...