XmlDocument.Save 方法 (System.Xml) | Microsoft Learn
Select XML Nodes by Attribute Value [C#] (这里面的例子挺有用的)
工作中相关的task需要对xml文件进行操作。记录一下相关的操作。最实用的应该是根据属性选择对应的节点,直接查找到之后插入生成的xml。
暂时的想法是 json -> jObject -> xml
其实没什么特殊点的,就当js操作html一样,看明白api,关于生成和遍历用深度优先就可。
插一个tips:节点下没内容就默认自闭和 <node/>
Select XML Nodes by Name [C#]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
To get all <Name> nodes use XPath expression /Names/Name
. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText
. See the example below.
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
The output is:
Name: John Smith Name: James White
elect XML Nodes by Attribute Value [C#]
This example shows how to select nodes from XML document by attribute value. Use method XmlNode.SelectNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
[XML]
<Names>
<Name type="M">John</Name>
<Name type="F">Susan</Name>
<Name type="M">David</Name>
</Names>
To get all name nodes use XPath expression /Names/Name
. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M']
.
[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(str); // suppose that str string contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");
foreach (XmlNode xn in xnList)
{
Console.WriteLine(xn.InnerText);
}
The output is:
John David