Reading from an attribute that might be missing in a xelement.add method in C#
-
26-05-2021 - |
문제
I am trying to create a XElement that reads from another XElement built from a file. Below is a sample of the code. My question is how do I code around a source attribute that might not be there? docHeader and invoice are XElements. When running this where one attribute is missing, I get a "Object reference not set to an instance of an object" error.
I guess I am asking is there a 'safe' way to read elements and attributes in case they are not there?
invoice.Add(
new XAttribute("InvoiceNumber", docHeader.Attribute("InvoiceNumber").Value),
new XAttribute("InvoiceSource", docHeader.Attribute("InvoiceSource").Value));
해결책
You are getting the exception because if the attribute InvoiceSource
is not present, docHeader.Attribute("InvoiceSource")
returns null. Simple check like
if (docHeader.Attribute("InvoiceSource") != null)
{
// here you can be sure that the attribute is present
}
will be sufficient.
다른 팁
Try breaking up the code so that it's more flexible and readable.
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));
}
제휴하지 않습니다 StackOverflow