我有一個xml,並且想要在任何地方替換屬性值,我發現它的元素名稱和屬性名稱保持不變但要替換的屬性值取決於其當前值。如果在屬性名稱保持不變但在不同節點中屬性名稱保持不變的情況下如何替換xml中的屬性值
原始的XML:
<Loan>
<status="First">
<report active = "True" raw_xml = "My name is abc and I am a doctor"/>
</status>
<status="Second">
<report active = "True" raw_xml = "My name is def and I am an actor"/>
</status>
<status="Third">
<report active = "True" raw_xml = "My name is xyz and I am a coder"/>
</status>
</Loan>
所要的輸出是:
<Loan>
<status="First">
<report active = "True" raw_xml = "My doctor"/>
</status>
<status="Second">
<report active = "True" raw_xml = "My actor"/>
</status>
<status="Third">
<report active = "True" raw_xml = "My coder"/>
</status>
</Loan>
我做一些操作來提取raw_xml的一部分,並取代其目前的價值。
我有代碼如何提取和替換值。
,但由於我使用的是單一的方法/默認情況下它與錯誤而失敗
序列包含一個以上的匹配元素
如何獲得通過,並遍歷每個它並使用Xdocument.descendants替換值..我不想使用Xpath作爲真正的XML我正在處理有這麼多的內部節點,並獲得每個屬性的xpath是非常艱難的。
我用於替換的當前代碼。
foreach (var report in doc.Descendants("report"))
{
var xms = "";
xms = report.Attribute("raw_xml").Value;
//My code to change to extract the required attribute value goes here..creating an xmsdoc variable and storing the output value for attribute in it
var element = doc.Descendants("report").Single(x => x.Attribute("active").Value == "True");
element.SetAttributeValue("raw_xml", xmsdoc.ToString());
}
XML是大小寫敏感的,從「報告」如此更改爲後代「報告」。 – jdweng
哎呀,是啊其實際報告..我輸錯了這裏 – HadoopAddict