他们说,一个人带着一只手表知道现在几点,而一个带着两只手表的人永远不确定。当谈到使用 XML 的选项时,我似乎有一个装满它们的抽屉。
值得我使用.Net 4。
我用一个简化的测试写入函数替换了我的原始代码,并将生成的 XML 字符串嵌入为注释。
我正在尝试向UserVar
下面的示例 XML 添加一个新节点。XML 来自一个商业程序,我对其设计没有任何意见。
当我尝试添加新条目时,最后会出现异常xDoc.Save()
此操作将创建一个构造不正确的文档。
理论上,我正在创建一个 XElement,其中包含与原始结构匹配的子元素,并尝试将其添加到现有文档中。从其他问题和示例可以看出其他人正在做什么。
我的代码低于 XML。该函数创建一个要添加到文档中的 XElement。
XML
<?xml version="1.0" encoding="UTF-8"?>
<Application>
<Vars>
<UserVars>
<UserVar>
<Name>"Quantity"</Name>
<Width>4</Width>
<VarValue>"1"</VarValue>
</UserVar>
<UserVar>
<Name>"Printers"</Name>
<Width>255</Width>
</UserVar>
<UserVar>
<Name>"Changed"</Name>
<Width>1</Width>
</UserVar>
<UserVar>
<Name>"Weight"</Name>
<VarValue>"450.1"</VarValue>
</UserVar>
</UserVars>
</Vars>
</Application>
代码
public static void TestWriteData(string xmlDocNm)
{
// Write a test value to an Acme UserVar in the exisiting XML
var xDoc = XDocument.Load(xmlDocNm); //This is your xml path value
XElement xVar = new XElement("UserVar");
// In this company's XML the strings have double quotes around them
xVar.Add((new XElement("Name", "\"Title\"")));
xVar.Add(new XElement("VarValue", "\"Paradise Lost\""));
XElement xElement = new XElement("Application",
new XElement("Vars",
new XElement("UserVars",
xVar)));
// XML Data in xElement - String data copied from the IDE watch
//<Application>
// <Vars>
// <UserVars>
// <UserVar>
// <Name>"Title"</Name>
// <VarValue>"Paradise Lost"</VarValue>
// </UserVar>
// </UserVars>
// </Vars>
//</Application>
xDoc.Add(xElement);
xDoc.Save(xmlDocNm); //Write the XML back to the file
}