我有这个 xml,我正在从一个 url 读取它,当我查看源代码时它看起来像这样:
<xml>
<root>
<item>
<id>1</id>
<name>Testing</name>
</item>
<item>
<id>2</id>
<name>Testing2</name>
</item>
</root>
</xml>
当我运行下面的代码时,它一直说缺少根元素?我确实有一个根元素。
public void myfunction()
{
WebRequest request = WebRequest.Create("http://www.site.com/file.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
string[] arr = XDocument.Load(dataStream).Root.Descendants("Name").Elements().Select(element => element.Value).ToArray(); //error says root element missing
foreach (var item in arr)
{
MessageBox.Show(item.ToString());
}
}
最佳答案
您的 xml 文件中没有 Name
元素。 Xml 区分大小写。您应该使用小写的 name
:
string[] arr = XDocument.Load(dataStream).Root
.Descendants("name")
.Select(name => (string)name)
.ToArray();
顺便说一句,您的 name
元素没有嵌套元素。
更新:如果您想获取name
元素的值,只需将这些元素转换为string
。您也可以在此处使用 Select(name => name.Value)
。只是不要尝试获取 name
的嵌套元素——它们没有。
关于c# - 缺少 xml 根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033392/