XElement 获取所有子元素节点名称和值

发布于 2024-10-04 11:12:50 字数 840 浏览 0 评论 0原文

我正在考虑类似这样的方法。 请告诉我这是否真的可以这样工作: 对于示例 XML:

<Root>
  <Node>
    <SubEl1>abc</SubEl1>
    <SubEl2>def</SubEl2>
    <SubEl3>123</SubEl3>
    <SubEl4>456</SubEl4>      
  </Node>
</Root>

想要进入 ,循环检查节点/元素名称并获取其值。 像这样,假设名称是“SubEl1”,则使用“abc”作为任务1,看到元素名称是“SubEl2”时,我执行任务2。必须检查所有子元素!

示例(非工作代码):

 //looping through 'Node' children
        switch(SubElName for 'Node element) 
        {
          case : 'SubEl1' 
            //Do Task1 using the SubEl1's value/TextName ...
          case: 'SubEl2' 
           //Task2 ...
          ... 
          case: default //Do default task.....
        } 
    //end loop

如果您能想到任何其他方法(XElement、XmlDocument、SelectNodes() 等),我们也将不胜感激!

I'm thinking of an approach something like this.
Please let me know if this can actually work this way:
For Sample XML:

<Root>
  <Node>
    <SubEl1>abc</SubEl1>
    <SubEl2>def</SubEl2>
    <SubEl3>123</SubEl3>
    <SubEl4>456</SubEl4>      
  </Node>
</Root>

Want to go into <Node>, loop through check for the node/element name and get it's value.
Something like this, say name is 'SubEl1' use 'abc' for task1, on seeing the element name is 'SubEl2' I do task2. All sub-elements have to be checked for!

Example (not working code):

 //looping through 'Node' children
        switch(SubElName for 'Node element) 
        {
          case : 'SubEl1' 
            //Do Task1 using the SubEl1's value/TextName ...
          case: 'SubEl2' 
           //Task2 ...
          ... 
          case: default //Do default task.....
        } 
    //end loop

If you can think of any other approach (XElement, XmlDocument, SelectNodes() etc., that will be appreciated too!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆橘 2024-10-11 11:12:50

对于此任务,您所需要做的就是简单地创建节点名称和节点值的列表/字典,然后您可以在交换机中使用它......

var list = from x in XElement.Load(**yourxmlfile**).Element("Node").Elements()
           select new
           {
              Name = x.Name,
              Value = (string)x
           };

现在您有一个名称、值对的列表可以简单地传递给你的 switch 方法。

For this task it looks like all you need to do is simply create a list/dictionary of the node name and the node value, you then can use that in your switch....

var list = from x in XElement.Load(**yourxmlfile**).Element("Node").Elements()
           select new
           {
              Name = x.Name,
              Value = (string)x
           };

now you have a list of Name, value pairs you can simply pass to your switch method.

逐鹿 2024-10-11 11:12:50

尚未使用过它,但 LINQ to XML 看起来非常棒。这里有一些链接。
MSDN 参考
迷上了 LINQ

Haven't made a use of it yet but LINQ to XML looks like all kinds of awesome. Here are some links.
MSDN Reference
Hooked On LINQ

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文