【问题标题】:add new Element to a specific part of xml tree将新元素添加到 xml 树的特定部分
【发布时间】:2017-01-24 13:19:08
【问题描述】:

我需要将新元素添加到 xml 树的特定部分,但我无法使其工作。

这是我的 xml 输入

    <structMap LABEL="Logical Structure" TYPE="LOGICAL">
  <div ID="DIVL1" TYPE="CONTENT">
    <div ID="DIVL2" TYPE="" DMDID="MODSMD_ARTICLE1" LABEL="">
      <div ID="DIVL3">
        <div ID="DIVL31" TYPE="TITLE" />
      </div>
    </div>
  </div>
</structMap>

这是我想要的输出

   <structMap LABEL="Logical Structure" TYPE="LOGICAL">
  <div ID="DIVL1" TYPE="CONTENT">
    <div ID="DIVL2" TYPE="" DMDID="MODSMD_ARTICLE1" LABEL="">
      <div ID="DIVL3">
        <div ID="DIVL31" TYPE="TITLE">
        <fptr>
          <area BETYPE="IDREF" FILEID="ALTO0011" BEGIN="P11_TB3"/>
        </fptr>
        </div>
      </div>
    </div>
  </div>
</structMap>

这是我的代码

var b = dc.Descendants().Attributes("TYPE").Where(ee => ee.Value == "TITLE").First();

我没有 b.AddFist。我怎样才能让它工作?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    当然,假设您使用的是 LINQ to XML,那么您没有b.AddFirst() 也就不足为奇了。 bXAttribute,而不是 XElement

    您似乎在寻找b.Parent.AddFirst()

    【讨论】:

      【解决方案2】:

      使用 xml linq:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Xml;
      using System.Xml.Linq;
      
      namespace ConsoleApplication1
      {
          class Program
          {
              const string FILENAME = @"c:\temp\test.xml";
              static void Main(string[] args)
              {
                  XDocument doc = XDocument.Load(FILENAME);
      
                  XElement title = doc
                     .Descendants("div")
                     .Where(x => (string)x.Attribute("TYPE") == "TITLE")
                     .FirstOrDefault();
      
                  title.Add(new XElement("fptr", new object[] {
                     new XElement("area", new object[] {
                         new XAttribute("BETYPE","IDREF"),
                         new XAttribute("FILEID","ALTO0011"),
                         new XAttribute("BEGIN","P11_TB3")
                     })
                  }));
              }
          }
      }
      

      【讨论】:

      • title.Add 可能有空异常。使用First 而不是FirstOrDefault
      猜你喜欢
      • 2012-10-31
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2013-07-19
      相关资源
      最近更新 更多