Pay attention to the following points when you query data using LINQ to XML.

Source: Internet
Author: User

Today, for project reasons, we need to use C # to parse the XML file. Because we use the 3.5 framework, we want to try the water with the LINQ to XML. So I tried it on msdn.

 

Code
Xelement Root = Xelement. Load ( " Projectsoruce. xml " );


Ienumerable< Xelement > Resources =
From El In Root. descendants ( " Task " )
Select El;
Foreach (Xelement el In Resources)
Console. writeline (EL );

The task element cannot be obtained. It's a bit confusing, and there are just a few examples on msdn. After debugging for an hour, I finally found that my XML has a namespace, And the namespace needs to be included during the query of the LINQ to XML.CodeIt should be written like this

@ "Http://schemas.microsoft.com/project"; is the namespace on my own XML

 

Code
Xnamespace NS =   @" Http://schemas.microsoft.com/project " ;

Xelement Root=Xelement. Load ("Projectsoruce. xml");


Ienumerable < Xelement > Resources =
From El In Root. element (NS +   " Tasks " ). Elements (NS +   " Task " )
Select El;
Foreach (Xelement el In Resources)
Console. writeline (EL );

// Pause the application
Console. Readline ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.