我有以下XML文件。我正在嘗試讀取dept元素的startDate節點,但不想讀取其他任何子元素(如「DeptRoles」)的「startDate」節點。閱讀XML節點
<dept operationalStatus="active" primaryRole="Admin" depChangeDate="20130420">
<startDate type="legal">20130401</startDate>
<endDate type="legal"></endDate>
<startDate type="operational">20130320</startDate>
<endDate type="operational"></endDate>
<DeptRoles>
<DeptRole name="Other dept" status="active">
<startDate type="legal">20130401</startDate>
<endDate type="legal"></endDate>
<startDate type="operational">20130320</startDate>
<endDate type="operational"/>
<isPrimary/>
</DeptRole>
</DeptRoles>
</dept>
這是我的C#代碼。這段代碼也得到了DeptRole startDate元素,我不想要。
public static List<organisation> Getorgdata(string data)
{
List<organisation> listorgdata = new List<organisation>();
XmlReader xmlReader = XmlReader.Create(new StringReader(data));
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
organisation record = new organisation();
if (xmlReader.HasAttributes && xmlReader.Name == "dept")
{
record.orgOperationalStatus = xmlReader.GetAttribute("operationalStatus");
record.orgLegalStatus = xmlReader.GetAttribute("legalStatus");
}
else if (xmlReader.Name == "name")
{
record.orgName = xmlReader.ReadElementString("name");
}
else if (xmlReader.Name == "startDate" || xmlReader.Name == "endDate")
{
if (xmlReader.GetAttribute("type") == "legal")
{
record.orgLegalStartDate = xmlReader.ReadElementString("startDate");
record.orgLegalEndDate = xmlReader.ReadElementString("endDate");
}
else if (xmlReader.GetAttribute("type") == "operational")
{
record.orgOperationalStartDate = xmlReader.ReadElementString("startDate");
record.orgOperationalEndDate = xmlReader.ReadElementString("endDate");
listorgdata.Add(record);
}
}
}
}
return listorgdata;
}
我該如何知道這個開始日期是否是合法的操作類型。如果我將deptid = anynumber添加到dept節點,可以請修改此查詢。如何使用這個Lin2Xml查詢來獲取例如deptid = anynumber的startDate元素 – user3202862