Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用XDocument编写XML不';我不可能加上元素_C#_Xml_Linq - Fatal编程技术网

C# 使用XDocument编写XML不';我不可能加上元素

C# 使用XDocument编写XML不';我不可能加上元素,c#,xml,linq,C#,Xml,Linq,我对C#and Linq是新手。我正在尝试将字典编写为XML文件。因此,我使用foreach循环将所有元素添加到根元素。这将添加到文档中。但它只将循环的最后一次迭代添加到文档中。我做错了什么 这是密码 public void ToXml(string xmlFile) { //Dictionary used: Values XDocument doc = new XDocument( new XDeclaration("1.

我对C#and Linq是新手。我正在尝试将字典编写为XML文件。因此,我使用foreach循环将所有元素添加到根元素。这将添加到文档中。但它只将循环的最后一次迭代添加到文档中。我做错了什么

这是密码

    public void ToXml(string xmlFile)
    {
        //Dictionary used: Values
        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", null));
        XElement xRoot = new XElement("RootElement");
        doc.Add(xRoot);
        Dictionary<double, double[]>.KeyCollection keys = Values.Keys;

        foreach(double key in keys)
        {
            XElement inner = new XElement("InnerElement",
                new XAttribute("value", key),
                new XElement("TestValue1", Values[key][0]),
                new XElement("Testvalue2", Values[key][1]),
                new XElement("TestValue3", Values[key][2]),
                new XElement("TestValue4", Values[key][3]),
                new XElement("TestValue5", Values[key][4]),
                new XElement("TestValue6", Values[key][5]));

            xRoot.Add(inner);
        }
        doc.Save(xmlFile);
    }
public void-ToXml(字符串xmlFile)
{
//使用的字典:值
XDocument doc=新XDocument(
新的XDeclaration(“1.0”,“utf-8”,null));
XElement xRoot=新的XElement(“根元素”);
单据新增(xRoot);
Dictionary.KeyCollection key=value.key;
foreach(双键输入键)
{
XElement-inner=新的XElement(“InnerElement”,
新XAttribute(“值”,键),
新的XElement(“TestValue1”,值[key][0]),
新的XElement(“Testvalue2”,值[键][1]),
新的XElement(“TestValue3”,值[键][2]),
新的XElement(“TestValue4”,值[键][3]),
新的XElement(“TestValue5”,值[键][4]),
新的XElement(“TestValue6”,值[键][5]);
xRoot.Add(内部);
}
doc.Save(xmlFile);
}
这是输出:

<?xml version="1.0" encoding="utf-8"?> 
<RootElement> 
    <InnerElement value="400"> 
        <TestValue1>0</TestValue1> 
        <Testvalue2>0</Testvalue2> 
        <TestValue3>200</TestValue3> 
        <TestValue4>0</TestValue4> 
        <TestValue5>100</TestValue5> 
        <TestValue6>491</TestValue6> 
    </InnerElement> 
</RootElement>

0
0
200
0
100
491

代码似乎正常,请检查
值是否仅包含一个键。是的,您是对的,忘记了输入错误。谢谢。代码似乎还可以,请检查是否只包含一个键。是的,您是对的,忘记了输入错误。谢谢