問題描述
我面臨的情況是使用 Linq 將 XML 文檔解析為對象.在解析過程中,我正在檢查以確保元素不為空,然后再繼續解析它們的值.有沒有辦法簡化這句話?
The situation I am faced with is parsing an XML document into an object using Linq. During the parse I am checking to make sure Elements are not null before proceeding to parse out their values. Is there anyway to simplify this statement?
var variable = (from x in xdoc.Descendants("Root")
select new AccountingResponse
{
NetCharge = x.Element("Charges") != null && x.Element("Charges").Element("NetCharge") != null ? x.Element("Charges").Element("NetCharge").Value : "0",
TotalCharge = x.Element("Charges") != null && x.Element("Charges").Element("TotalCharge") != null ? x.Element("Charges").Element("TotalCharge").Value : "0"
}).SingleOrDefault();
總而言之,我不想繼續檢查每行是否存在節點.我知道我可以在解析之前測試該節點是否存在,但可能還有其他數據需要解析以創建 AccountingResponse,我想避免一次只解析一部分 XML 的 if 語句.
To summarize, I do not want to continue to check if the nodes exist on each line. I know I can test to see if the node exists prior to the parsing, but there may be other data that needs parsed to create the AccountingResponse and I want to avoid if statements that only parse a portion of the XML out at a time.
或者也許我做錯了,有更好的方法!
Or perhaps I'm doing this completely wrong and there's a better way!
推薦答案
一個簡單的選擇是使用 Elements
而不是 Element
- 這將返回一個零長度的序列如果元素不存在.所以你可以使用:
One simple option is to use Elements
rather than Element
- that will return a zero-length sequence if the element isn't present. So you can use:
from x in xdoc.Descendants("Root")
select new AccountingResponse
{
NetCharge = x.Elements("Charges")
.Elements("NetCharge")
.Select(y => (int) y)
.FirstOrDefault(),
TotalCharge = x.Elements("Charges")
.Elements("TotalCharge")
.Select(y => (int) y)
.FirstOrDefault(),
}).SingleOrDefault();
(請注意,您的原始代碼不會編譯,因為 Value
是一個字符串,而 0 是一個 int...)
(Note that your original code wouldn't compile, as Value
is a string whereas 0 is an int...)
這篇關于帶有檢查空元素的 XML 到 LINQ的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!