【问题标题】:c# How to know the root and child node names dynamically in xml in silverlightc#如何在silverlight的xml中动态知道根节点和子节点的名称
【发布时间】: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.LinqSystem.Xml.Linq 不会涵盖所有内容。

标签: c# xml silverlight xml-parsing linq-to-xml


【解决方案1】:

我还不能发表评论,所以我要在这里写:System.Xml.Linq 是你需要的 XmlDocument.Descendants,而不是 System.Linq

Get All node name in xml in silverlight

^这就是你要找的。 我使用了这段代码,它打印了节点名称就好了。

    string xml = "<A><B><C>C1</C><D>D1</D></B><Separator>S1</Separator><B><C>C2</C><D>D2</D></B></A>";
    XDocument doc = XDocument.Parse(xml);
    foreach (XElement child in doc.Root.DescendantsAndSelf())
    {
        Console.WriteLine(child.Name.LocalName);
    }

【讨论】:

  • 请查看问题中添加的快照。我已经有了
  • 实际上我添加了 Sysestem.Linq (它丢失并且它工作:P)但仍然有一个错误。错误 1 ​​类型“char”不能用作泛型类型或方法“System.Xml.Linq.Extensions.Descendants(System.Collections.Generic.IEnumerable)”中的类型参数“T”。没有从 'char' 到 'System.Xml.Linq.XContainer' 的装箱转换。
  • @Ansad 感谢您的回答,但它是一个银色应用程序。它不支持 XmlDocument。
  • @user234839 因为您处理的是字符串而不是文件:var doc = XDocument.Parse(xmlstring)。该链接大部分都有您的答案。然而,它会一次性打印所有内容不是您想要的分层方式。
  • 把代码稍微改一下:foreach (XElement child in doc.Root.Nodes()) { Console.WriteLine(child.Name.LocalName); }
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多