我想在 XML中的最后一个子元素之后添加元素.但是我收到了一个错误. XML ID="Microsoft Search Thesaurus" thesaurus xmlns="x-schema:tsSchema.xml" diacritics_sensitive0/diacritics_sensitive expansion subInternet Explorer
<XML ID="Microsoft Search Thesaurus"> <thesaurus xmlns="x-schema:tsSchema.xml"> <diacritics_sensitive>0</diacritics_sensitive> <expansion> <sub>Internet Explorer</sub> <sub>IE</sub> <sub>IE5</sub> </expansion> <replacement> <pat>NT5</pat> <pat>W2K</pat> <sub>Windows 2000</sub> </replacement> <expansion> <sub>run</sub> <sub>jog</sub> </expansion> <expansion> <sub>home</sub> <sub>house</sub> </expansion> </thesaurus> </XML>
我的代码在下面,我在调试代码时遇到了这个错误.
<同义词库> element具有指定命名空间的xmlns属性,因此您需要将命名空间添加到所有元素名称.此外,如果您想要新的< expansion>,则应使用Add而不是AddAfterSelf.元素出现在<同义词库>里面而不是在它之后.InvalidOperationException was unhandled.
Sequence contains no elements.
XDocument doc = XDocument.Load("tseng.xml"); //load the xml file. IEnumerable<XElement> MemberList = doc.Element("XML").Elements("thesaurus"); var Member = new XElement("expansion", new XElement("sub", "home"), new XElement("sub", "house") ); MemberList.Last().AddAfterSelf(Member); //add node to the last element. doc.Save("tseng.xml");此错误适用于特定行:
MemberList.Last().AddAfterSelf(Member);我不知道这个代码有什么问题.如何在最后一次< expansion>之后添加元素节点到我的XML文件?
你能帮我解决这个问题吗?谢谢.
XNamespace ns = "x-schema:tsSchema.xml"; IEnumerable<XElement> MemberList = doc.Element("XML").Elements(ns + "thesaurus"); var Member = new XElement(ns + "expansion", new XElement(ns + "sub", "home"), new XElement(ns + "sub", "house")); MemberList.Last().Add(Member); //add node to the last element.