English 中文(简体)
如何利用C#和XML,立即将儿童因素纳入其中?
原标题:How to get the immediate child elements of the root element using C# and XML?
 <Document>
    <Heading1>
         <text>Heading Title</text>   
         <para>para1</para>
         <para>para2</para>
         <para>para3</para>
     </Heading1>
    <Heading1>
         <text>2nd Heading Title</text>   
         <para>para4</para>
         <para>para5</para>
         <para>para6</para>
         <Heading2>
              <text>3rd Heading Title</text>   
              <para>para4</para>
              <para>para5</para>
         </Heading2>       
     </Heading1>
 </Document>

This is XML Document. Now, i want to parse this XML file using C# (4.0). Here, I want to get all the Heading1 elements without using that element name in my program. For example, don t use document.GetElementsByTagName("Heading1");. How i get it. Guide me get out of this issue.

增资 在这方面。

最佳回答

• 借助LLL,你可以:

var headings = yourXDocument.Root.Elements();

使用Nodes(Elements()还将退回案文和评论,这些内容显然不是你想要的。

问题回答

可通过http://msdn.microsoft.com/en-us/library/bb342765.aspx” rel=“nofollow” Elements(。 采用LINQ至XML的方法。

XDocument doc = ...;

var query = doc.Root.Elements();

如果您重新使用<代码>XmlDocument,则这项工作:

var elements = doc.SelectNodes("/*/*");

That finds all child elements of the top-level element irrespective of any of their names. It s usually safer to specify the names if you know them, so that elements with unexpected names don t get returned in your list - use /Document/Heading1 to do this.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签