问题描述
大家好,
如何写特定节点???
how to write in the specific node???
C#中是否有一个函数写一个函数 ;在xml文件中获取数组或列表值???
is there a function in C# a write function taking a array or a list values in xml file ???
函数"XmlTextWriter"获取字符串值。
the function "XmlTextWriter" taking string value.
此代码从特定节点读取值:
this code to read value from specific node :
XDocument doc = XDocument.Load(" C:\\用户\\Sami \\Desktop \\ ssaa.xml");
              var result = doc.Descendants(" title")。ToList();
              listBox1.Items.Add(result [0] .Value);
XDocument doc = XDocument.Load("C:\\Users\\Sami\\Desktop\\ssaa.xml");
var result = doc.Descendants("title").ToList();
listBox1.Items.Add(result[0].Value);
现在我想写这个值"结果"在同一个xml文件中的特定节点中。
and now i want to write this value "result" in the specific node in the same xml file.
推荐答案
使用
string.Join(",quot;,stringArray)展平您的数组以使其适合单个节点。例如,
Use string.Join(",", stringArray) to flatten your array to fit it into a single node. E.g.
namespace ConsoleCS
{
using System;
using System.Xml.Linq;
using System.Xml.XPath;
public class Program
{
public static void Main(string[] args)
{
string[] stringArray = new string[] { "A", "B", "C" };
XDocument document = XDocument.Parse("<root><a></a><b></b></root>");
XElement node = document.XPathSelectElement("/root/a");
node.Value = string.Join(",", stringArray);
Console.WriteLine(document);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
或者你想要每个阵列有一个子节点item?
Or do you want one sub-node per array item?
namespace ConsoleCS
{
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
public class Program
{
public static void Main(string[] args)
{
string[] stringArray = new string[] { "A", "B", "C" };
XDocument document = XDocument.Parse("<root><a></a><b></b></root>");
XElement node = document.XPathSelectElement("/root/a");
stringArray.ToList()
.ForEach(item => { node.Add(new XElement("item", item)); });
Console.WriteLine(document);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
这篇关于C#中的xmltextwriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!