how to read values in this xml file?

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <ProductVersion>9.0.30729</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
  </PropertyGroup>
</Project>


I am using the following code to read the value in the <ProductVersion>
tag in the above xml file:

----------------------------------
XPathDocument doc = new XPathDocument(myxml.xml);
XPathNavigator nav = doc.CreateNavigator();
			
XPathExpression expr; 
expr = nav.Compile("/Project/PropertyGroup/ProductVerion");
XPathNodeIterator iterator = nav.Select(expr);

iterator.MoveNext(); //actually in a loop
XPathNavigator nav2 = iterator.Current.Clone();
Console.WriteLine("version " + nav2.Value.ToString());
----------------------------------

this works if I leave out 

xmlns="http://schemas.microsoft.com/developer/msbuild/2003"

from the <Project> tag.  But the actual file that I am trying to read
contains the "xmlns ..." text and my routine won't read the
ProductVersion tag.  I am hoping that the methods I am using here are
outdated and there are newer methods/classes I could use to perform this
read.  Any help appreciated. 

Thanks

Rich

*** Sent via Developersdex http://www.developersdex.com ***
0
Rich
11/19/2009 10:23:28 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

6 Replies
885 Views

Similar Articles

[PageSpeed] 8

OK.  I found this routine which sort of does the trick

XmlTextReader reader = new XmlTextReader ("data5.xml");
while (reader.Read()) 
 {switch (reader.NodeType) 
   {
     case XmlNodeType.Element: // The node is an element.
       Console.Write("<" + reader.Name);
       Console.WriteLine(">");
         break;
     case XmlNodeType.Text: //Display the text in each element.
       Console.WriteLine (reader.Value);
         break;
    case XmlNodeType.EndElement: //Display the end of the element.
      Console.Write("</" + reader.Name);
      Console.WriteLine(">");
        break;
    }
  }
Console.ReadLine();
}

Except that I want to isolate the <ProductVersion> value.  Well, at
least I'm making some progress.

Rich

*** Sent via Developersdex http://www.developersdex.com ***
0
Rich
11/19/2009 10:35:26 PM
Rich P wrote:
> [...]
> ----------------------------------
> XPathDocument doc = new XPathDocument(myxml.xml);
> XPathNavigator nav = doc.CreateNavigator();
> 			
> XPathExpression expr; 
> expr = nav.Compile("/Project/PropertyGroup/ProductVerion");
> XPathNodeIterator iterator = nav.Select(expr);
> 
> iterator.MoveNext(); //actually in a loop
> XPathNavigator nav2 = iterator.Current.Clone();
> Console.WriteLine("version " + nav2.Value.ToString());
> ----------------------------------
> 
> this works if I leave out 
> 
> xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
> 
> from the <Project> tag.  But the actual file that I am trying to read
> contains the "xmlns ..." text and my routine won't read the
> ProductVersion tag. [...]

I think the problem you're running into is that with the xmlns 
declaration, the element names actually implicitly include that XML 
namespace, and so the namespace has to be included in the fully 
qualified element name for your XPath expressions.

Unfortunately, as far as I know, there's no way to get XPathNavigator to 
handle this automatically, because while the namespace itself is the URI 
declared in the "xmlns" attribute, XPath requires a prefix, not the full 
URI.  You can't just stick the URI in front of the element name and have 
it work.

But, you can get it to work in a "semi-automatic" way by creating an 
XmlNamespaceManager that maps a prefix of your choosing to the URI for 
the namespace, and then use that prefix in your XPath expression.

See below for a concise-but-complete code example that demonstrates the 
technique (my apologies in advance for broken string literals...they 
tend not to survive newsgroup copy-and-paste very well, but I assume you 
can make the necessary edits after the fact if there's a problem).

You can also read about it here:
http://msdn.microsoft.com/en-us/library/e5t11tzt.aspx

If that doesn't answer your question, you really need to post a 
concise-but-complete code example yourself, so that we can see what your 
code is really doing and why it doesn't work.

Pete


using System;
using System.Xml.XPath;
using System.Xml;
using System.IO;

namespace TestXmlWithNamespace
{
     class Program
     {
         static void Main(string[] args)
         {
             string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                 "<Project ToolsVersion=\"3.5\" DefaultTargets=\"Build\"" +
                 " 
xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">" +
                     "<PropertyGroup>" +
                         "<ProductVersion>9.0.30729</ProductVersion>" +
                         "<SchemaVersion>2.0</SchemaVersion>" +
                         "<OutputType>WinExe</OutputType>" +
 
"<AppDesignerFolder>Properties</AppDesignerFolder>" +
                     "</PropertyGroup>" +
                 "</Project>";

             XPathDocument doc = new XPathDocument(new 
StringReader(strXml));
             XPathNavigator nav = doc.CreateNavigator();
             XmlNamespaceManager manager = new 
XmlNamespaceManager(nav.NameTable);

             manager.AddNamespace("default", 
"http://schemas.microsoft.com/developer/msbuild/2003");

             foreach (XPathNavigator xpath in 
nav.Select("/default:Project/default:PropertyGroup/default:ProductVersion", 
manager))
             {
                 Console.WriteLine(xpath.Name);
             }

             Console.WriteLine("done");
             Console.ReadLine();
         }
     }
}
0
Peter
11/20/2009 12:34:11 AM
On 2009-11-19, Rich P <rpng123@aol.com> wrote:
><?xml version="1.0" encoding="utf-8"?>
><Project ToolsVersion="3.5" DefaultTargets="Build"
> xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
>  <PropertyGroup>
>     <ProductVersion>9.0.30729</ProductVersion>
>     <SchemaVersion>2.0</SchemaVersion>
>     <OutputType>WinExe</OutputType>
>     <AppDesignerFolder>Properties</AppDesignerFolder>
>  </PropertyGroup>
></Project>
>
>
<snip>

>
> *** Sent via Developersdex http://www.developersdex.com ***

Well, if you using 2008, then I would do it something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication52
{
    class Program
    {
        private const string Xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""3.5"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
  <PropertyGroup>
    <ProductVersion>9.0.30729</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
  </PropertyGroup>
</Project>";

        static void Main ( string[] args )
        {
            XNamespace dName = "http://schemas.microsoft.com/developer/msbuild/2003";
            XElement doc = XElement.Load ( new StringReader ( Xml ) );
            var s = ( from version in doc.Descendants ( dName + "ProductVersion" ) select version.Value ).FirstOrDefault ();
            Console.WriteLine ( s );
        }
    }
}

-- 
Tom Shelton
0
Tom
11/20/2009 12:41:50 AM
I would use the reader anyway, should be far better performance wise.


"Rich P" <rpng123@aol.com> wrote in message 
news:%23ecRsbWaKHA.4312@TK2MSFTNGP04.phx.gbl...
> <?xml version="1.0" encoding="utf-8"?>
> <Project ToolsVersion="3.5" DefaultTargets="Build"
> xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
>  <PropertyGroup>
>    <ProductVersion>9.0.30729</ProductVersion>
>    <SchemaVersion>2.0</SchemaVersion>
>    <OutputType>WinExe</OutputType>
>    <AppDesignerFolder>Properties</AppDesignerFolder>
>  </PropertyGroup>
> </Project>
>
>
> I am using the following code to read the value in the <ProductVersion>
> tag in the above xml file:
>
> ----------------------------------
> XPathDocument doc = new XPathDocument(myxml.xml);
> XPathNavigator nav = doc.CreateNavigator();
>
> XPathExpression expr;
> expr = nav.Compile("/Project/PropertyGroup/ProductVerion");
> XPathNodeIterator iterator = nav.Select(expr);
>
> iterator.MoveNext(); //actually in a loop
> XPathNavigator nav2 = iterator.Current.Clone();
> Console.WriteLine("version " + nav2.Value.ToString());
> ----------------------------------
>
> this works if I leave out
>
> xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
>
> from the <Project> tag.  But the actual file that I am trying to read
> contains the "xmlns ..." text and my routine won't read the
> ProductVersion tag.  I am hoping that the methods I am using here are
> outdated and there are newer methods/classes I could use to perform this
> read.  Any help appreciated.
>
> Thanks
>
> Rich
>
> *** Sent via Developersdex http://www.developersdex.com *** 


0
Paul
11/20/2009 3:03:44 PM
Thanks all for your replies.  The manager suggestion worked as
advertised and the xml.linq method also worked well and less code.

Now I have a wealth of methods for reading xml.  Question:  is it
accurate that the XmlTextReader method will outperform xml.linq? I do
have hundreds (if not more) xml files that I will have to read.  

Thanks again all for the help.

Rich

*** Sent via Developersdex http://www.developersdex.com ***
0
Rich
11/20/2009 5:23:25 PM
Rich P wrote:
> Thanks all for your replies.  The manager suggestion worked as
> advertised and the xml.linq method also worked well and less code.
> 
> Now I have a wealth of methods for reading xml.  Question:  is it
> accurate that the XmlTextReader method will outperform xml.linq? I do
> have hundreds (if not more) xml files that I will have to read.  

It just depends.  In theory, the linear behavior of the XmlTextReader is 
more efficient and thus faster.  But it's also less convenient to use, 
and for small files, so much of the time cost of dealing with the file 
is in just the basic processing of opening the file, reading something 
from it, and closing it, costs that are incurred no matter what 
technique you use to access the data in the file.

And of course, if you need random access to the data in the file, 
XmlTextReader becomes unwieldy and potentially much less efficient.

If you have long files, and you know in advance that the data you need 
to access is always close to the beginning of the file, I would say that 
XmlTextReader is going to be a slam dunk for better performance.  But 
otherwise, there are too many variables to predict whether there will be 
a significant, or any, improvement in performance.  You're better off 
using the API that is most convenient, and then watching for performance 
issues in case they do occur.

Pete
0
Peter
11/20/2009 6:46:27 PM
Reply:

Similar Artilces:

How can I open a file saved in Pub 2000 version 6 in Pub 2000 ver.
The file is saved in Publisher 2000 v6 and I am trying to open it with Publisher 2000 v9. can this be done? Hi LaTrice (LaTrice @discussions.microsoft.com), in the newsgroups you posted: || The file is saved in Publisher 2000 v6 and I am trying to open it || with Publisher 2000 v9. can this be done? No. There is no such thing as Publisher 2000 v9, nor is there a version 9 of Publisher, yet. Verify the version of Publisher that you have, and also verify the version of Publisher that you received the file from then post back. -- Brian Kvalheim Microsoft Publisher MVP http://www.publi...

Setting series values on Excel Chart
Hi I'm struggling very hard in getting beyond this error when trying to use VB to generate a chart from data previously inserted into the sheet. Unable to set the Values property of the Series class. The code works absolutely fine in XL2007 but I am having to port it back to 2003 and the inference is that its empty values that cause it to hiccup - something I cannot avoid. My code is: 1. Retrieve selected data from database and place it at the top of the sheet 2. Add The Chart 3. Iterate through the data (amount can be variable depending upon user inputs) For j as i...

Timestamp value of GINA window presentation
I am currently troubleshooting slow logon times for a client with computer infrastructure spread across the globe. Before I start invesagating I want to create a baseline for logon times. I have modified the clients logon script to record when it starts and when it ends. I am using the computers tick count to record how long the computer has been on, but realize that there is a space of time between the user authenicating to the computer (control-alt-delete) and when the logon script starts, if the customer turns his computer on and then leave for an extended period of time I ...

Nested schema bug? Project compiles, but doesn't read XML properly
We've run into an issue with VS2005 (at least I *think* it's an issue with Visual Studio) and one of our XML dataset schemas. We're trying to add a nested XML element to an existing element, but even though the project compiles fine, the XML document is not being read into a dataset properly. This is a trimmed-down sample of our current (working) XML document: <?xml version="1.0" encoding="utf-8"?> <AppMasterDataset xmlns="..."> <Aspects> <Key>...</Key> <Label>...</Label> <Aspect> ...

data value in Form field if no table entry
I have a form with a field which pulls through and concentenates 2 fields called [ContactFirstname] and [ContactLastName]from my table There are however some customers for whom I do not have names and therefore instead I would like Sir/Madam to appear in the field in the form I think I have seen this done somewhere using ELSE? but can't find it Any help/ideas gratefully received Perhaps something like this: Nz(Trim([ContactFirstname] & " " + [ContactLastName]), "Sir/Madam") -- Allen Browne - Microsoft MVP. Perth, Western Australia Tips for Access use...

how to query my web site from VBA and return a value to VBA
Hello All, From VBA I would like send a value to my web site, and have it return a value. I've learned how to use FollowHyperlink to send a value to an ASP script, but how can the ASP script send a value back to VBA?? Thanks, Brian Austin, TX You can use xmlhttp to make a request to your web page: '********************************************************* Sub Tester() MsgBox WebResponse("http://www.mydomain.com/myactualpage.asp? info=3Dblah") End Sub Private Function WebResponse(sURL As String) As String Dim XmlHttpRequest As Object Se...

rules and alerts after read
I want to create rules where emails are sent to particular folders after they have been read. How do I do this? The rules and alerts section in my outlook 2003 version doesn't seem to allow me to do this. Rules act on mail when received or sent, not after being read. --=81 Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. All unsolicited mail sent to my personal account will be deleted without reading. =20 After furious head scratching, Turtle asked: | I want to create rules where emails are sent to particular folders | after they have been...

automatically naming files for savingb
Hi, for delivery notes i would like excel to look in the relative directory for a given customer, ie if C4 contains superspecs, files relating to this account would be in c:\work\superspecs\ files are named superspecsdel0001,superspecsdel0002.......etc superspecsinv0001...etc for delivery notes and invoices. what i would like is a line (or more) to add to a macro which will look in the appropriate directory, add 1 to the last four digits of the last file, enter this number into a cell on the sheet and save the new file with the appropriate name, then close the file. is this possible, or alte...

why do changes only save locally on networked excel file?
why do changes only save locally on networked excel file? ...

Assign values for one column to another.
Hi I have in column T certain numbers and texts that that I require to assign a value to as below, in the adjacent column. Again any pointers would be much appreciated. Kind Regards Celticshadow T U 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 10 F 10 UR 10 U 10 R 10 S 10 L 10 P 10 PU 10 BD 10 D 10 Well, imagine that two-column table occupies cells Y1:Z20. Put this formula in U1: =3DVLOOKUP(T1,Y$1,Z$20,2,0) and copy down. Hope this helps. Pete On Oct 14, 4:26=A0pm, Celticshadow <Celticsha...@discussions.microsoft.com> wrote: > Hi > >...

Excel formulation to automate values
Hi there, I have a little problem on arranging a small multi-worksheet excel here. Let me explain in a short way then give some details on it. I am trying to make an offers recordsheet which has two worksheets in it. One for products(and their base prices) and an offer sheet. I would like to use a bit dynamic data here. So when I type the name of the product excel would give me the price from other worksheet. in details; Prices worksheet is something like: A B 1 Product BasePrice 2 mouse 5 3 keyboard 8 4 ... And the ...

Outlook should keep files in the clipboard after closing a window
When you open a message (in a new window) in Outlook 2007, and copy one or more files contained in this message, and then close the window, the file is not kept in the clipboard. I have to copy the file and paste it before closing the window. ---------------- 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 ...

I want to read,but:
The web display: Directory Listing Denied This Virtual Directory does not allow contents to be listed. could you tell how to access another web like this? "LeeTow" <fbjlt@pub3.fz.fj.cn> wrote in message news:eDQ5RlJmEHA.3612@TK2MSFTNGP12.phx.gbl... > The web display: > Directory Listing Denied > This Virtual Directory does not allow contents to be listed. > could you tell how to access another web like this? > > looks like the link got wrapped, you may have to copy it out and put it back together... or you could try this: http://tinyurl.com/3mtvv ...

Deleted file in Outlook
I accidentaly deleted a folder in Outlook 2003 and am wondering if it possible to retreive it. Thank you, Karl youthminman@yahoo.com <youthminman@yahoo.com> wrote: > I accidentaly deleted a folder in Outlook 2003 and am wondering if it > possible to retreive it. Unless you permanently deleted it (i.e., held down Shift when pressing Delete), it will be in your Deleted items folder, unless you've emptied that folder. If you have emptied it, other suggestions depend on knowing what data store you're using (PST or Exchange mailbox). -- Brian Tillman ...

How do I get total value data labels in a stacked bar chart?
I have a 3-D stacked bar chart with four series and I want to have the total value in each category be displayed in a data label. Can I do this, and if so, how?? Hi, This should help http://www.andypope.info/charts/StackColTotal.htm Cheers Andy blemerson wrote: > I have a 3-D stacked bar chart with four series and I want to have the total > value in each category be displayed in a data label. Can I do this, and if > so, how?? -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info Thanks, Andy. The CFO is thrilled. Heather "Andy Pope" wrote: > Hi, >...

XML File Converter for MS 2004
Version: 2004 Operating System: Mac OS X 10.4 (Tiger) Processor: intel I'm a high school teacher. I write power points on MS 2004 on my Mac and transfer them to my school's PC that has MS 2003. This worked great, with exception of minor formatting changes, until a month ago. Power points that I previously opened on that PC, along with new ones, would not open - this is disasterous for instruction. My tech says 1) the school's PC may have had updates that caused the new problem and 2) that I should install the Open XML File Converter for Mac's MS 2004. I'm concerned tha...

how do I transfer file from Clipboard to an e-mail message
How do I transfer a file from Outlook clipboard or C drive to the body of an e-mail message NOT as an attachment. thanks you would need to open the file and copy the contents. -- Diane Poremsky [MVP - Outlook] Author, Teach Yourself Outlook 2003 in 24 Hours Coauthor, OneNote 2003 for Windows (Visual QuickStart Guide) Need Help with Common Tasks? http://www.outlook-tips.net/beginner/ Outlook Tips: http://www.outlook-tips.net/ Outlook & Exchange Solutions Center: http://www.slipstick.com Subscribe to Exchange Messaging Outlook newsletter: EMO-NEWSLETTER-SUBSCRIBE-REQUEST@PEACH.EASE.LSOF...

Transferring files to a new computer
Hi - I'm in the process of configuring my new Windows XP with MSFT Small Biz. I was running Windows 98 and using Outlook 2000. Now I want to copy all my old emails, folders, addresses etc. into the new version of Outlook 2003 but I can't seem to find it. It's not recognizing my saved files as .PST files. Does anyone know how to do this? Thanks, daviskho "daviskho" <anonymous@discussions.microsoft.com> wrote in message news:052801c3dbb0$e46e5970$a101280a@phx.gbl... > Hi - I'm in the process of configuring my new Windows XP > with MSFT Small Biz. ...

Too large to send, yet the file gets saved.
I noticed that a user's mailbox grew from 100KB to 400KB in a few days. This got my attention. I pokjed around and found that he had tried to zip a really big file and send it to his AOL account. (we won't talk about what was in that single file that would not compress al that well :-) ) The file was 161MB (obviously this is larger than global message delivery default) and it was in both his sent items and found in the bounce-back message from the system administrator: This message is larger than the current system limit or the recipient's mailbox is full. Create a shorter messa...

Capital One giving me corrupt Money import files
Money is saying the files I get from Capital One credit card are corrupt. Some months import fine, while others I get an error. I try to get support from Capital One, but they keep giving me the runaround. Anything I can do with Money to get this to work? I have about 50 transactions a month and rather not input these manually! -Max Max, The problem is that there's a character in the statement you're getting from Capital One that Money is choking on. I've run in to the same issue...save the statement from Capital One to your hard drive and edit it by hand. Search for &qu...

Opening multiple workbooks through code and copying values
Help! the following code 'kinda sorta' does what I want, but it has 3 problems. 1. Instead of going on to the next file if the file doesn't exist, it pastes the data from the previous file. 2. It closes the workbook into which I am compiling data instead of just the ones I am copying from. 3. Everytime it closes a file, it asks the question about 'large amounts of data in the clipboard.' Thanks, Pam Here is the code: Private Sub cmdCreate_Click() On Error GoTo Report_Err Dim myPath As String Dim myReport As Object Dim mySheet As String Dim myRow As Integer Dim x...

jpg files
I have had several users experiencing problems opening pictures from Outlook 2000. Their O/S is XP Pro. Any ideas? Thank You, Jamie ...

Copying Very Large files
Would there be any performance gain if we used win2008R2 rather than Windows 7 at each end for copying large(2-5GB batches). -- Craig On Wed, 24 Feb 2010 11:56:55 -0600, "News" <nf@no.com> wrote: >Would there be any performance gain if we used win2008R2 rather than >Windows 7 at each end for copying large(2-5GB batches). > >-- Craig > I doubt it but the performance will differ in ways that depend upon the file size not just the total bytes. You may find some clues in http://blogs.technet.com/markrussinovich/archive/2008/02/04/28261...

Help setting a File Name
hi experts I'm having trouble with the following: Cell J1 of Sheet1 contains a date, say Dec. 15, 2009. Sheet1 has a 'Save' button called cmbSave. When I click cbmSave, I'd like the SaveAs... dialog to be shown with the suggested File Name showing as 'POS_Summary_091215.xls' . In other words, I'd like the suggested file name to start with 'POS_Summary_', and to end with the J1 date in yymmdd format. Can this be done? thank you in advance Cinnie -- cinnie Sub newdate() Dim d As Date, s As String d = Range("J1").Va...

Web link to Excel 97 file
I've got a link to an Excel '97 file from a ColdFusion page. The link works fine the first time I click it. However, if I close the file down and click the link again, I get a message saying 'Cars.xls is being modified by (my user name). Would you like to open as read only?' I can open the file as read only, but am wondering why I get this message, even when I'm not modifying it? I've had other users try and it works the same way for them, except it tells them they're the one currently modifying it. We're using Internet Explorer 5.5 and Windows 20...