[英]How to set attribute to an XmlNode object which is not set to an instance or object. c#
I cannot figure out how to set a default value to an XmlNode
. 我无法弄清楚如何为
XmlNode
设置默认值。
I have an XmlNode
called RequirementMinTime
and I want to set it to the value of "0" when that node is not in the xml document. 我有一个名为
RequirementMinTime
的XmlNode
并且当该节点不在xml文档中时,我想将其设置为“ 0”。 Here is the code I'm trying which is not working. 这是我正在尝试的代码,无法正常工作。
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");
}
I am getting the following error in the if statement 我在if语句中收到以下错误
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
“ System.NullReferenceException:'对象引用未设置为对象的实例。'”
this is the object declaration: 这是对象声明:
public static XmlNode RequirementMinTime
{
get;
set;
}
You need to create the node, otherwise you can not set a value (assuming your XmlDocument
is named xmlDoc
: 您需要创建节点,否则您将无法设置值(假设您的
XmlDocument
名为xmlDoc
:
if (GlobalNode.SelectSingleNode("MinTimeMs") == null)
{
RequirementMinTime = xmlDoc.CreateElement("MinTimeMs");
RequiredMinTime.Value = "0";
}
else
{
RequirementMinTime = GlobalNode.SelectSingleNode("MinTimeMs");
}
here is the solution 这是解决方案
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.