[英]Writing to xml from C#
I have a question about writing to xml with C#. 我有一个关于使用C#编写xml的问题。 I want this kind of structure; 我想要这种结构;
<directory_move>
<folder_path>
<source_path>...</source_path>
..
..
</folder_path>
<properties>
<aaabbcc>....</aaabbcc>
..
..
</properties>
</directory_move>
I tried so much but could not obtain what I want. 我做了很多尝试,但无法获得想要的东西。 Can you give an advice, how can i do that? 您能给我个建议吗?
this is my code 这是我的代码
XElement element = new XElement("DIRECTORY_MOVE");
foreach (string sourceDirName in listArray)
{
element.Add(new XElement("SOURCE_PATH", sourceDirName));
}
element.Add(new XElement("DESTINATION_PATH", destination));
if (rdbtnDoLater)
{
element.Add(new XElement("RDBTNDOLATER", "checked"));
}
if (rdbtnDoImmediately)
{
element.Add(new XElement("RDBTNDOIMMEDIATELY", "checked"));
}
if (chkIsOverwrite)
{
element.Add(new XElement("CHKISOVERWRİTE", "checked"));
}
if (chkExitWhenFinish)
{
element.Add(new XElement("CHKEXITWHENFINISH", "checked"));
}
if (chkFolderQuestion)
{
element.Add(new XElement("CHKFOLDERQUESTION", "checked"));
}
Using Linq to XML 使用Linq到XML
XElement example =
new XElement("directory_move",
new XElement("folder_path",
new XElement("source_path", "..."),
new XElement("source_path", "...")
),
new XElement("properties",
new XElement("aaabbcc", ...)
)
);
example.WriteToFile(...)
Edit: The issue with your code is that you're adding everything to the root element, so everything will be children of this root. 编辑:代码的问题是您要将所有内容添加到根元素,因此所有内容都是该根的子级。
What you need to do is reproduce the hierarchy, as I did in my example. 正如我在示例中所做的那样,您需要做的是重现层次结构。
XElement root = new XElement("DIRECTORY_MOVE");
XElement folderPath = new XElement("folder_path");
root.Add(folderPath)
foreach (string sourceDirName in listArray)
{
folderPath.Add(new XElement("SOURCE_PATH", sourceDirName));
}
and so on... 等等...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.