更新时间:2023-11-05 16:42:28
这里是使用 XElement 的简单示例:
Here is a simple example using XElement:
string TestXml = @"<root>
<one>first_one</one>
<two>second_one</two>
<tree>third_one</tree>
<four>fourth_one</four>
<five>fifth_one</five>
<six>sixth_one</six>
</root>";
XElement x = XElement.Parse(TestXml);
var one = x.Element("one");
one.Value = "CHANGED ONE";
x.Element("two").Remove();
foreach (var item in x.Elements())
{
Debug.Print(item.ToString());
}
如果您更喜欢使用 XDocument ,这没什么不同,您将必须记住使用根,请参见此处的说明: ^ ]
但是正如MSDN文档所述:
If you prefer using XDocument, this is not much different, you will have to remember to use the root, see explanation here: Querying an XDocument vs. Querying an XElement (C#) | Microsoft Docs[^]
But as the MSDN documentation states:
在许多情况下,您的应用程序将不需要您创建文档.通过使用XElement类,可以创建XML树,向其添加其他XML树,修改XML树并保存.
In many cases, your application will not require that you create a document. By using the XElement class, you can create an XML tree, add other XML trees to it, modify the XML tree, and save it.
^ ]
请注意,使用.NET 3.0或更低版本时,您只需要 XmlDocument .
XDocument Class Overview (C#) | Microsoft Docs[^]
Note that you only need XmlDocument when using .NET version 3.0 or lower.
请参考MSDN文档:XmlDocument类(System.Xml)| Microsoft文档 [ ^ ],尤其是 ^ ]和Edit nodes
.
您可能对使用XPath导航选择节点 [
Please, refer MSDN documentation: XmlDocument Class (System.Xml) | Microsoft Docs[^], especially Find nodes[^] andEdit nodes
.
You might be interested in Select Nodes Using XPath Navigation[^]
According to the OP requirements (posted in solution 3):
我想保持xml文件的原样
1.我唯一需要的是创建一个类,如读取一,二,树或所有值元素
2.一类更新一,二,树或所有值元素
I Want to keep the xml file like it is
1. The only think I need is to create class like read one, two, tree or all values elements
2. one class to update one, two, tree or all values elements
我建议将您的xml结构更改为此:
I''d recommend to change your xml structure to this one:
<MyItems>
<MyItem id = "first">first one</Item>
<MyItem id = "second">first one</Item>
<MyItem id = "third">first one</Item>
<MyItem id = "fourth">first one</Item>
<!-- and so on -->
</MyItems>
表示单个项目的类可能类似于:
A class representing single item this may look like:
public class MyItem
{
public string id = "first";
public string text = "first_one";
}
最后,您需要一个MyItem
的集合.
有关更多详细信息,请阅读我的提示:自定义的完整示例类集合序列化和反序列化 [ ^ ].没错,它是用Vb.net编写的,但是您必须处理它,因为Vb.net与C#非常相似.
Finally, you need a collection of MyItem
.
For further details, please read my tip: A Complete Sample of Custom Class Collection Serialization and Deserialization[^]. True, it''s written in Vb.net, but you have to handle it, because Vb.net is pretty similar to C#.