【问题标题】:How to set attribute value for existing XML element [duplicate]如何为现有 XML 元素设置属性值 [重复]
【发布时间】:2018-02-15 17:11:12
【问题描述】:

我有一个现有的 XML 文件,我想更新它的一些属性。我用谷歌搜索了很多类似的问题和答案,但我没有运气。

<?xml version="1.0"?>
<system ExportDate="2/15/2018" ExportTime="11:56 AM EST" DateFormat="MM/dd/yyyy" NumberFormat="HH:mm:ss " SchemaValidation="true" ExportVersion="2016.1.SP1710.57 [Build 82] - 27 September 2017 (01:30 IST)" xmlns="http://www.mentor.com/harness/Schema/LibrarySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mentor.com/harness/Schema/LibrarySchema file:/C:/MentorGraphics/VeSys_Client/dtd/LibrarySchema.xsd" XMLVersion="1.6">
  <librarymaterial librarymaterial_id="XXX" description="YYY" materialcode="ZZZ" />
 </system>

我正在尝试为某些属性设置新值。
对于root,我没有问题

xmlDoc.DocumentElement.SetAttribute("ExportDate", DateTime.Now.ToShortDateString());
xmlDoc.DocumentElement.SetAttribute("ExportTime", DateTime.Now.ToShortTimeString() + " EST");

但是,当我尝试不同的方法但没有希望时

方法一:

XmlNode node = xmlDoc.SelectSingleNode("/system/librarymaterial");
node.Attributes["librarymaterial_id"].Value=_librarymaterial_id;

错误:

System.NullReferenceException: '对象引用未设置为对象的实例。'

节点为空。

方法二:

var nodes = xmlDoc.SelectNodes("/system/librarymaterial");
foreach (XmlElement n in nodes)
{
    n.SetAttribute("librarymaterial_id", _librarymaterial_id);
}

这不会产生错误,但librarymaterial_id 不会得到更新。

【问题讨论】:

  • 请注意,system 有一个命名空间。你需要一个命名空间管理器
  • @ThomasWeller 感谢您的纠正。我删除了我的评论。
  • 正如@ThomasWeller 指出的那样,您需要一个命名空间管理器来执行此操作,请仔细阅读此答案:stackoverflow.com/a/1089210/4222487
  • 我正在设置它 - 谢谢

标签: c# xml


【解决方案1】:
        XmlNodeList dataNodes = doc.GetElementsByTagName("librarymaterial");

        for (int i = 0; i < dataNodes.Count; i++)
        {
            XmlAttribute attr = dataNodes[i].Attributes["librarymaterial_id"];
            attr.Value = "USA";
        }

试试这个代码。

【讨论】:

  • 它有效,因此至少有 2 个解决方案。谢谢!
  • 一旦您在变量中拥有节点列表,您就可以使用它。因此,同一个问题可以有多种解决方案。谢谢!
  • 不!为什么要遍历所有节点,然后将第一个修改 n 次?
  • Typeo,请立即查看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多