【发布时间】:2014-07-04 00:18:11
【问题描述】:
我将 xml 存储在一个字符串中,假设如下:
String xmlString =
<A>
<B>
<C>C1</C>
<D>D1</D>
</B>
<Separator>S1</Separator>
<B>
<C>C2</C>
<D>D2</D>
</B>
</A>
我想从 c# 代码中知道每个子节点名称的名称。
我的意思是我不会有 xml 代码,它会随机出现,所以我不知道 xml 结构是什么,我想知道所有的子节点名称,例如 A、B、Cand D。
我的意思是我想要从头/父(在 lmy xml 中)开始到最后(我的意思是在我的 xml 中)结束并像A,B,C,D,Separator, then again B ,C,D 这样的所有节点一一打印。
我尝试的是这样的:
IEnumerable<XElement> de = from el in xmlstring.Descendants() select el;
foreach (XElement el in de)
{
Debug.WriteLine(el.Name);
}
但它给出了错误:
Error 1 The type 'char' cannot be used as type parameter 'T' in the generic type or method 'System.Xml.Linq.Extensions.Descendants<T>(System.Collections.Generic.IEnumerable<T>)'. There is no boxing conversion from 'char' to 'System.Xml.Linq.XContainer'.
Error 2 Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>'. 'Select' not found. Are you missing a reference or a using directive for 'System.Linq'?
这两个错误都对应于 xmlstring.Descendants(),Visual Studio 带有红色下划线。
我有以下参考:(我的意思是我已经有必要的参考,如 Linq、xml 等):
注意:我在silverlight工作,我必须用c#编写这段代码。
谢谢你会很有帮助的。
【问题讨论】:
-
“提供一段代码供参考”听起来像是“为我做我的工作”。你有没有尝试过任何东西?如果您可以使用 LINQ to XML,这非常简单 - 例如,查看
Descendants方法。也不清楚标题中的“根子节点”是什么意思.... -
只是为了澄清,节点名称,不是值。对吗?
-
@JonSkeet root child 表示 root 和 child 都必须逐步打印。
-
@user234839:所以你的意思是“所有节点名称”?目前还不清楚...
-
您需要在解决方案和代码文件中引用
System.Linq。System.Xml.Linq不会涵盖所有内容。
标签: c# xml silverlight xml-parsing linq-to-xml