.net 下对于XML的相关操作及资源

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.Selec­tNodes 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
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

董厂长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值