我使用下面的代码行获取许多XML文件的值。但是,我注意到一些XML文件缺少" DateOfBirth"抛出值的元素不能为null。有没有办法忽略元素并在XML文件中缺少元素时分配空值?如你所见,我有一个循环,然后我将这些记录添加到网格中。如果缺少DateOfBirth元素,它将忽略此记录而不将其添加到DataSet。我希望它仍然添加FirstName和LastName并将DOB留空。
foreach (object o in listBox2.Items)
{
DataSet objDataSet = new DataSet();
objDataSet.ReadXml(folder + "\\" + o.ToString(), XmlReadMode.InferSchema);
try
{
List<object> firstNames = objDataSet.Tables["FirstName"].AsEnumerable().Select(r => r["Part"]).ToList();
List<object> lastNames = objDataSet.Tables["LastName"].AsEnumerable().Select(r => r["Part"]).ToList();
List<object> dob = objDataSet.Tables["DateOfBirth"].AsEnumerable().Select(r => r["FullDate"]).ToList();
添加XML:
<OmdCds xmlns="cds"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cdsd="cds_dt"
xsi:schemaLocation="cds ontariomd_cds.xsd">
<PatientRecord>
<Demographics>
<Names>
<cdsd:LegalName namePurpose="L">
<cdsd:FirstName>
<cdsd:Part>SARAH</cdsd:Part>
<cdsd:PartType>GIV</cdsd:PartType>
<cdsd:PartQualifier>BR</cdsd:PartQualifier>
</cdsd:FirstName>
<cdsd:LastName>
<cdsd:Part>GOMEZ</cdsd:Part>
<cdsd:PartType>FAMC</cdsd:PartType>
<cdsd:PartQualifier>BR</cdsd:PartQualifier>
</cdsd:LastName>
<cdsd:OtherName>
<cdsd:Part>GABRIELA</cdsd:Part>
<cdsd:PartType>GIV</cdsd:PartType>
<cdsd:PartQualifier>BR</PartQualifier>
</cdsd:LastName>
</cdsd:LegalName>
</Names>
<DateOfBirth>
<cdsd:FullDate>1950-03-26</cdsd:FullDate>
</DateOfBirth>
答案 0 :(得分:0)
我自己解决了上述问题。我创建一个bool方法来检查元素是否存在。基于true或false,我要么忽略以获取元素的值。
public bool IsNodeExist(string fileName)
{
bool bState = false;
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
//Select the node with the matching attribute value.
XmlNode nodeToFind;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
namespaceManager.AddNamespace("cdsd", "cds_dt");
namespaceManager.AddNamespace("cds", "cds");
nodeToFind = doc.DocumentElement.SelectSingleNode("./cds:PatientRecord/cds:Demographics/cds:DateOfBirth", namespaceManager);
if (nodeToFind == null)
{
bState = true;
}
return bState;
}