C# Xdocument解析文件和读取值
我有下面的示例XML,我需要检索以下两个字段txJu和ddate的值C# Xdocument解析文件和读取值,c#,.net,linq-to-xml,C#,.net,Linq To Xml,我有下面的示例XML,我需要检索以下两个字段txJu和ddate的值 var xdoc=XDocument.Load(文件); 字符串txJu=xdoc.Root.Element(“comp”).Attribute(“txJu”).Value; 字符串ddate=xdoc.Root.Element(“Doc”).Attribute(“ddate”).Value; 您的代码有几个问题。您的Root元素不包含comp节点,Doc元素本身是Root,string ddate=string value
var xdoc=XDocument.Load(文件);
字符串txJu=xdoc.Root.Element(“comp”).Attribute(“txJu”).Value;
字符串ddate=xdoc.Root.Element(“Doc”).Attribute(“ddate”).Value;
您的代码有几个问题。您的Root
元素不包含comp
节点,Doc
元素本身是Root,string ddate=string value=…
是无效的C声明。
您可以根据以下内容修改代码
var compElement=xdoc.Root?.genderantsandself(“comp”).FirstOrDefault();
字符串txJu=compElement?属性(“txJu”)?值;
字符串ddate=xdoc.Root?.Attribute(“ddate”)?.Value;
字符串值=ddate;
使用方法获取过滤后的
comp
元素的集合,并使用其中的第一个元素。直接在Root
元素中访问ddate
属性。使用?
避免可能出现的空引用异常Root没有comp
element@PavelAnikhouski-那你能帮我怎么得到那些值吗?我的日期陈述错了,我在问题中修正了。它可以很好地获取日期值,但txJu返回为null。我正在使用genderantsandself
方法成功获取12.96
值
<Doc id="580171" ddate="2019-06-21" >
<ref dtRef="2019-08-21">
<dr>
<cr>
<pj>
<pr>
<dDup txJu="0.00" txFi="0.00" txcOp="0.00" />
<comp txJu="12.96" txFi="2.45" txOp="0.00" />
</pr>
</pj>
</cr>
</dr>
</ref>
</Doc>
var xdoc = XDocument.Load(file);
string txJu = xdoc.Root.Element("comp").Attribute("txJu").Value;
string ddate = xdoc.Root.Element("Doc").Attribute("ddate").Value;