如何将属性设置为未设置为实例或对象的 XmlNode 对象。 C#

How to set attribute to an XmlNode object which is not set to an instance or object. c#

我不知道如何将默认值设置为 XmlNode

我有一个名为 RequirementMinTimeXmlNode,当该节点不在 xml 文档中时,我想将其设置为值“0”。这是我正在尝试的代码,它不起作用。

        XmlReader reader = XmlReader.Create(xmlpath, settings);
        XmlDocument doc = new XmlDocument();

        doc.Load(reader);

       if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
        {
            RequirementMinTime.Attributes["MinTimeMs"].Value = "0";
        }
        else
        {
            RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
        }

我在 if 语句中收到以下错误

"System.NullReferenceException: 'Object reference not set to an instance of an object.'"

这是对象声明:

    public static XmlNode RequirementMinTime
    {
        get;
        set;
    }

你需要创建节点,否则你不能设置值(假设你的XmlDocument被命名为xmlDoc:

if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
{
    RequirementMinTime = xmlDoc.CreateElement("MinTimeMs");
    RequiredMinTime.Value = "0";
}
else
{
    RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
}

这是解决方案

    XmlReader reader = XmlReader.Create(xmlpath, settings);
    XmlDocument doc = new XmlDocument();

    doc.Load(reader);

   if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
    {
        XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "MinTimeMs", "");
        newNode.InnerText = "0";
        GlobalNode.AppendChild(newNode);    
        RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
    }
    else
    {
        RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
    }