c# - 将属性添加到 XML 文件 Linq C#

标签 c# xml linq

我想为我所有的 XML 文件添加一个测试(通用)属性。这样当我想测试它们时,我可以将它用作通用属性。

我尝试了 CreateAttribute,但 Linq 无法识别它

我尝试了“xElement.Add(new XAttribute("Test", value));”但它也没有用 有什么建议吗?

谢谢

这里有一段代码例子

    public void updateXmlFile(string strFileName)
    {
        XDocument oXDoc = XDocument.Load(strFileName);
        XElement oDcElement = oXDoc.Root.FirstNode as XElement;

        //Generate a Unique String to replace the original attribute value
        string newValue = GetUniqueKey();

        //oDcElement.Add(new XAttribute("Test", newValue)); /*NullReferenceException*/

        oDcElement.Attribute("Remark").Value = newValue; //This changes only the Remark Attribute
        oXDoc.Save(strFileName);                         //which isn't available in all XMLs

    }

我想为通过此方法传递的 XML 添加一个额外的公共(public)值,并为其赋予一个随机值

我的目标是能够对 XML 进行更改,然后将其与另一个文件夹中的原始副本进行比较

最佳答案

使用 SetAttribute:

oDcElement.SetAttributeValue("Test", newValue);

关于c# - 将属性添加到 XML 文件 Linq C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3565038/

相关文章:

c# - 没有 ASP.NET MVC 的捆绑和缩小

c# - 仅当存在时从行首删除指定文本 (C#)

c# - 事件处理程序中的 "reentrant call to SetCurrentCellAddressCore"- 仅当单元格行索引和列索引相等时

安卓 : Initialize XML object from programmatically which has parameter

c# - 为什么我在此 LINQ 查询中得到 'cannot convert type ' IEnumerable<myType >' to ' myType'?

c# - 使用集合参数对集合属性进行 Linq 查询

c# - for循环中的迭代变量什么时候递增

c# - 如何在 PictureBox C# 中绘制对象?

xml - 具有标记化和不同值的复杂 XSLT 转换

php - 在 simplexml (php) 中创建 XML