2017-06-16 31 views
0

我已经开始将我的设置写入节点中,例如。编写适当的xml缺失值白色节点

XmlDocument xmlDoc = new XmlDocument(); 
XmlNode rootNode = xmlDoc.CreateElement("Propertise"); 
xmlDoc.AppendChild(rootNode); 

XmlNode userNode = xmlDoc.CreateElement("Property"); 
XmlAttribute attribute = xmlDoc.CreateAttribute("default"); 
attribute.Value = "4.5"; 
userNode.Attributes.Append(attribute); 
attribute = xmlDoc.CreateAttribute("amount"); 
attribute.Value = "4.5"; 
userNode.Attributes.Append(attribute); 
attribute = xmlDoc.CreateAttribute("name"); 
attribute.Value = "some setting name"; 
userNode.Attributes.Append(attribute); 
rootNode.AppendChild(userNode); 

但是这在XML中缺少一个结束属性标记。

我必须更改哪些部分以完成缺失标记?

+0

我建议将'xmlDoc.AppendChild(rootNode);'移到'rootNode.AppendChild(userNode);'后面。 –

回答

0

它不缺少结束属性标记。它是自闭标签,因为它没有任何子节点。

<?xml version="1.0" encoding="utf-8"?> 
<Propertise> 
    <Property default="4.5" amount="4.5" name="some setting name" /> 
                   ^
                   | 
                  It is closed here. 
</Propertise> 

一旦你添加一些子节点内将在另一行结束标签,就像这里:

<?xml version="1.0" encoding="utf-8"?> 
<Propertise> 
    <Property default="4.5" amount="4.5" name="some setting name"> 
    <OtherProperty /> 
    </Property> 
</Propertise> 

您也可能想使用的,而不是XmlDocument的下一次的XDocument,因为我认为这使得创建xml文档变得更简单:

XDocument doc = new XDocument(
new XElement("Properties", 
new XElement("Property", 
    new XAttribute("default", "4.5"), 
    new XAttribute("amount", "4.5"), 
    new XAttribute("name", "some setting name"))));