我有一個XML文件,我必須從XML中提取所有屬性值。我已經嘗試了下面的一個,但我需要Linq。任何人都可以指導我如何做到這一點。通過使用Linq到XML的XML文件獲取屬性值的所有屬性值
示例XML
<MapFile>
<Import>
<field name1="BorrowId" name2="EMPLID" />
<field name1="Firstname" name2="COMPLETENAME" />
<field name1="Address" name2="Address" Reference="Location" />
</Import>
<Location>
<Lookup Key="CC" Replace="1" />
<Lookup Key="CE" Replace="2" />
</Location>
</MapFile>
預期結果
[0]:
CurrentVal = "BorrowId"
NewVal = "EMPLID"
Reference = null
ReferenceList = null
[1]:
CurrentVal = "Firstname"
NewVal = "COMPLETENAME"
Reference = null
ReferenceList = null
[2]:
CurrentVal = "Address"
NewVal = "Address"
Reference = "Location"
ReferenceList = [0]:
Key = "CC"
Value = "1"
[1]:
Key = "CE"
Value = "2"
代碼
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@sPath);
var attrValues = xmlDoc.GetElementsByTagName("field");
List<MapFileModel> MapFileMod = new List<MapFileModel>();
foreach (XmlNode x in attrValues)
{
MapFileModel _objMapFile = new MapFileModel();
if (x.Attributes["name1"] != null)
{
_objMapFile.CurrentVal = x.Attributes["name1"] != null ? x.Attributes["name2"].Value : null;
_objMapFile.NewVal = x.Attributes["name2"] != null ? x.Attributes["name2"].Value : null;
_objMapFile.Reference = x.Attributes["Reference"] != null ? x.Attributes["Reference"].Value : null;
}
MapFileMod.Add(_objMapFile);
}
嗯,我會使用LINQ to XML,這是開始*多*比'XmlDocument'更清潔的API,以及更多的LINQ友好。現在,根據您的代碼判斷,您看起來比「我必須提取所有屬性值」要求更多 - 請在您的問題中表達這些要求。目前尚不清楚你現在要求的是什麼。 –
對不起,我沒有看到任何其他要求提取屬性值的數量。 – DonMax
那麼爲什麼你的代碼有所有這些字符串文字來尋找*特定*屬性?只需提取「所有屬性值」就像doc.Descendants()一樣簡單。SelectMany(x => x.Attributes()。Select(a => a.Value))''。但這不是你想要的,我懷疑 - 這隻會給你一個「IEnumerable」,這是所有屬性值的序列。如果您提供一個簡短的示例XML文檔和預期的輸出,它將會有所幫助... –