加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在最后一个特定节点/元素之后插入XML元素

发布时间:2020-12-16 23:06:19 所属栏目:百科 来源:网络整理
导读:我想在 XML中的最后一个子元素之后添加元素.但是我收到了一个错误. XML ID="Microsoft Search Thesaurus" thesaurus xmlns="x-schema:tsSchema.xml" diacritics_sensitive0/diacritics_sensitive expansion subInternet Explorer/sub subIE/sub subIE5/sub /
我想在 XML中的最后一个子元素之后添加元素.但是我收到了一个错误.

<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>

我的代码在下面,我在调试代码时遇到了这个错误.

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"),"house")
             );
MemberList.Last().AddAfterSelf(Member);  //add node to the last element.
doc.Save("tseng.xml");

此错误适用于特定行:

MemberList.Last().AddAfterSelf(Member);

我不知道这个代码有什么问题.如何在最后一次< expansion>之后添加元素节点到我的XML文件?

你能帮我解决这个问题吗?谢谢.

解决方法

<同义词库> element具有指定命名空间的xmlns属性,因此您需要将命名空间添加到所有元素名称.此外,如果您想要新的< expansion>,则应使用Add而不是AddAfterSelf.元素出现在<同义词库>里面而不是在它之后.

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","house"));
MemberList.Last().Add(Member);  //add node to the last element.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读