【问题标题】:What's the easiest way to add attribute to XML in a text box in c#?在 c# 的文本框中向 XML 添加属性的最简单方法是什么?
【发布时间】:2015-02-11 06:57:41
【问题描述】:

我有以下格式的 XML,可以手动或脚本输入到文本框中:

<instructions>
  <step index="1">Do this</step>
  <step index="2">Do that</step>
</instructions>

我希望能够单击一个按钮以向指令元素添加一个属性,这样所有 XML 都将保持不变,但文本框中生成的 XML 将如下所示:

<instructions iterations="3">
  <step index="1">Do this</step>
  <step index="2">Do that</step>
</instructions>

我能够将 XML 放入 XmlDocument,但在添加元素并将结果返回到文本框中时遇到了问题。

任何帮助将不胜感激!

这是我目前根据反馈获得的代码:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(textBoxInstructions.Text);

var attr = xmlDoc.CreateAttribute("iterations");
attr.InnerText = "3";
string strNewXML = xmlDoc.InnerXml;

textBoxInstructions.Text = strNewXML;

但是,旧的和新的一样。

【问题讨论】:

    标签: c# xml xmldocument


    【解决方案1】:

    你可以试试这段代码

    XmlDocument doc = new XmlDocument(); 
    doc .LoadXml(textBoxInstructions.Text); 
    
    var attr = doc.CreateAttribute("iterations");
    attr.InnerText = "3";
    doc .Attributes.Append(attr);
    
     StringWriter sw = new StringWriter();
     XmlTextWriter xw = new XmlTextWriter(sw);
     doc.WriteTo(xw);
     yourTextBox.Text = sw.ToString();
    

    对于元素

    var xmlElement = doc.CreateElement("...");
    xmlElement.SetAttribute("Name","Value");
    

    【讨论】:

    • 这并没有将属性添加到指令元素中。我在 XML 中的任何地方都看不到它。
    • 元素 已经存在,所以我不想创建一个新元素吗?
    • 我尝试了第一个代码,但从未添加该属性。我调试过,运行前后的doc是一样的。
    • 我试图将我的代码复制到 cmets,但失败了。我会把它放在一个新的帖子中。
    • 我想将它保存回文本框——不是 XML 文件。
    【解决方案2】:

    尝试在按钮的点击事件上调用以下函数。

     public void populateNewXML()
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(textBoxInstructions.Text);
                var attr = xmlDoc.CreateAttribute("iterations");
                attr.InnerText = "3";
                xmlDoc.GetElementsByTagName("instructions")[0].Attributes.Append(attr);
                textBoxInstructions.Text = xmlDoc.InnerXml;
            }
    

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 2011-04-02
      • 2010-09-23
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2019-07-06
      相关资源
      最近更新 更多