C#循环通过XML节点 [英] C# loop trough XML nodes
本文介绍了C#循环通过XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想通过xml循环一些节点。
我的xml文件如下所示:
<? xml 版本 = 1.0 编码 = utf-8 ? > ;
< RoundType >
< name >
StartRound
< / name >
< span class =code-keyword>< ActionGroups >
< group >
< 名称 >
STANDART
< / name >
< 路径 >
STANDART
< / path >
< / group >
< / ActionGroups >
< / RoundType >
i试过这个:
使用系统;
使用 System.Collections.Generic;
使用 System.IO;
使用 System.Text;
使用 System.Xml;
使用 System.Xml.Linq;
命名空间 SurvivalGamesLib
{
class ActionHandler
{
public 列表< XmlDocument> LoadActions(XDocument roundType)
{
List< XmlDocument> actions = new 列表< XmlDocument>();
List< string> groups = new List< string>();
foreach ( var node roundType.Element( RoundType)中的class =code-keyword>。元素( ActionGroups)。元素( group))
{
Console.WriteLine( 测试跨度>);
Console.WriteLine(node.Element( name)。Value);
}
返回行动;
}
}
}
但是当我运行它我总是得到这个错误:
System.NullReferenceException:'对象引用未设置为对象的实例。'
System.Xml.Linq.XContainer.Element(...)返回null。
是否有人知道解决方案为此?
我尝试了什么:
搜索谷歌。但我发现的解决方案在我的情况下不起作用。
解决方案
试试这个:
< pre lang =C#> foreach ( var node in roundType.Root.Descendants( group))
{
groups.Add(node.Element( name)。Value);
}
或:
List< string> groups = roundType.Root
.Descendants( group)
。选择(node = > node.Element( name )。值)
.ToList();
so im tring to to loop trough some nodes in xml.
my xml file looks like this :
<?xml version="1.0" encoding="utf-8" ?>
<RoundType>
<name>
StartRound
</name>
<ActionGroups>
<group>
<name>
STANDART
</name>
<path>
STANDART
</path>
</group>
</ActionGroups>
</RoundType>
i have tried this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace SurvivalGamesLib
{
class ActionHandler
{
public List<XmlDocument> LoadActions(XDocument roundType)
{
List<XmlDocument> actions = new List<XmlDocument>();
List<string> groups = new List<string>();
foreach (var node in roundType.Element("RoundType").Element("ActionGroups").Elements("group"))
{
Console.WriteLine("test");
Console.WriteLine(node.Element("name").Value);
}
return actions;
}
}
}
but when i run it i always get this error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Xml.Linq.XContainer.Element(...) returned null.
is there someone that knows a solution for this ?
What I have tried:
searching google. but al the solutions i found did not work in my case.
解决方案
Try this:
foreach (var node in roundType.Root.Descendants("group")) { groups.Add(node.Element("name").Value); }
or:
List<string> groups = roundType.Root .Descendants("group") .Select(node => node.Element("name").Value) .ToList();
这篇关于C#循环通过XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文