簡體   English   中英

從C#的xelement.add方法中可能缺少的屬性讀取

[英]Reading from an attribute that might be missing in a xelement.add method in C#

我正在嘗試創建一個XElement,該XElement將從另一個從文件構建的XElement中讀取。 下面是代碼示例。 我的問題是如何圍繞可能不存在的源屬性進行編碼? docHeader和發票是XElement。 在缺少一個屬性的情況下運行此命令時,出現“對象引用未設置為對象實例”錯誤。

我想我問的是是否存在一種“安全”的方式來讀取元素和屬性,以防它們不存在?

invoice.Add(
    new XAttribute("InvoiceNumber", docHeader.Attribute("InvoiceNumber").Value), 
    new XAttribute("InvoiceSource", docHeader.Attribute("InvoiceSource").Value));

之所以會出現異常,是因為如果屬性InvoiceSource不存在,則docHeader.Attribute("InvoiceSource")將返回null。 簡單檢查像

if (docHeader.Attribute("InvoiceSource") != null)
{
    // here you can be sure that the attribute is present
}

就足夠了。

嘗試分解代碼,使其更靈活,更易讀。

var src = docHeader.Attribute("InvoiceSource");
var num = docHeader.Attribute("InvoiceNumber");

if(src != null && num != null)
{
  invoice.Add(
    new XAttribute("InvoiceNumber", num.value), 
    new XAttribute("InvoiceSource", src.value)); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM