[英]Get xml node value c#
Let us consider the following xml as 让我们考虑以下xml作为
<?xml version="1.0" encoding="UTF-8" ?>
<response success="true">
<struct>value</struct>
</response>
while parsing i am getting following error as 解析时我得到以下错误
Root element is missing.
the code which i used was 我使用的代码是
foreach (XElement carselement in xdoc.Descendants("response"))
{
String value= carselement.Element("struct").Value;
}
waiting for your solutions 等待您的解决方案
The XML input is not as expected (it is "empty") and the exception occurs during XDocument.Load
(or XDocument.Parse
, etc). XML输入与预期不符(它为“空”),并且在
XDocument.Load
(或XDocument.Parse
等)期间发生了异常。
Ultimately xdoc
does not contain what is expected - and the "suspect" lines never even run; 最终,
xdoc
不包含预期的内容-并且“可疑”行甚至永远不会运行。 again, this Exception is caused when the XML is parsed , not when it is enumerated/navigated. 同样,此异常是在解析 XML时引起的,而不是在枚举/导航时引起的。 This scenario should be easily identified with an attached debugger or stack-trace.
应该通过附加的调试器或堆栈跟踪轻松识别这种情况。
Here is some minimal code that can be run in LINQPad as C# statements. 这是一些可以在LINQPad中作为C#语句运行的最小代码。 I've modified it just enough to display nicely with dump.
我已经对其进行了修改,足以与转储很好地显示。 Note that it runs as expected .
请注意, 它按预期运行 。
var xmlStr = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<response success=""true"">
<struct>value</struct>
</response>";
var xdoc = XDocument.Parse(xmlStr);
xdoc.Descendants("response")
.Select(e => e.Element("struct").Value)
.Dump();
Here is how the exception can be caused (and it has nothing to do with Descendants
or other enumeration/navigation): 这是引发异常的方式 (与
Descendants
或其他枚举/导航无关):
var xmlStr = @"<?xml version=""1.0"" encoding=""UTF-8"" ?>";
var xdoc = XDocument.Parse(xmlStr);
// --> XmlException: Root element is missing
Maybe your XML is over simplified, and looks like this: 也许您的XML过于简化了,看起来像这样:
<!-- example -->
<?xml version="1.0" encoding="UTF-8" ?>
<response success="true">
<struct>value1</struct>
</response>
<response success="true">
<struct>value2</struct>
</response>
<response success="false">
<struct>value3</struct>
</response>
In this case you are missing a <responses></responses>
which wraps around the response
array of elements. 在这种情况下,您会丢失一个
<responses></responses>
,它围绕元素的response
数组。
BTW, your code should work also, if your XML file is really what you quote here. 顺便说一句,如果您的XML文件确实是您在此处引用的内容,那么您的代码也应该工作。 Do you try to manipulate the XML too?
您是否也尝试操纵XML?
XDocument xdoc = XDocument.Load(filePath);
if (xdoc == null) return;
XElement response = xdoc.Descendants("response").FirstOrDefault();
XElement structElement = response.Descendants("struct").FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.