https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-queries-linq-to-xml

In This Section

Topic Description
How to: Find an Element with a Specific Attribute (C#) Shows how to find a particular element that has an attribute that has a specific value.
How to: Find an Element with a Specific Child Element (C#) Shows how to find a particular element that has a child element that has a specific value.
Querying an XDocument vs. Querying an XElement (C#) Explains the differences between writing queries on an XML tree that is rooted in XElement and writing queries on an XML tree that is rooted in XDocument.
How to: Find Descendants with a Specific Element Name (C#) Shows how to find all the descendants of an element that have a specific name. This example uses the Descendants axis.
How to: Find a Single Descendant Using the Descendants Method (C#) Shows how to use the Descendants axis method to find a single uniquely named element.
How to: Write Queries with Complex Filtering (C#) Shows how to write a query with a more complex filter.
How to: Filter on an Optional Element (C#) Shows how to find nodes in an irregularly shaped tree.
How to: Find All Nodes in a Namespace (C#) Shows how to find all nodes that are in a specific namespace.
How to: Sort Elements (C#) Shows how to write a query that sorts its results.
How to: Sort Elements on Multiple Keys (C#) Shows how to sort on multiple keys.
How to: Calculate Intermediate Values (C#) Shows how to use the Let clause to calculate intermediate values in a LINQ to XML query.
How to: Write a Query that Finds Elements Based on Context (C#) Shows how to select elements based on other elements in the tree.
How to: Debug Empty Query Results Sets (C#) Shows the appropriate fix when debugging queries on XML that is in a default namespace.

See Also

实战

XElement Element = XElement.Load(filePath);

删除带namespace的节点

   private void AddNewtonSoftJson()
{
string namespaceStr=@"{urn:schemas-microsoft-com:asm.v1}";
string assemblyName = "Newtonsoft.Json";
IEnumerable<XElement> newtonSoftJsonElements =
from el in Element.Elements("runtime").Elements($"{namespaceStr}assemblyBinding").Elements($"{namespaceStr}dependentAssembly")
where (string)el?.Element($"{namespaceStr}assemblyIdentity")?.Attribute("name") == assemblyName
select el;
foreach (XElement el in newtonSoftJsonElements)
{
el.RemoveAll();
}
}

批量删除system.web下的某些节点

 public void RemoveSystemWebControls()
{
var list = new List<string>()
{
"CMS.PortalControls",
"CMS.Controls",
"CMS.FormControls",
"CMS.ExtendedControls",
"System.Web.UI.DataVisualization.Charting",
"System.Web.UI.WebControls"
};
IEnumerable<XElement> targetElements =
from el in Element.Elements("system.web").Elements("pages").Elements("controls").Elements("add")
where list.Contains(el?.Attribute("namespace")?.Value)
select el;
foreach (XElement el in targetElements)
{
el.Remove();
}
}

System.Xml.Linq.XElement.RemoveAll  一般用不到这个,都是用另外一个

https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.removeall?view=netframework-4.7#System_Xml_Linq_XElement_RemoveAll

Removes nodes and attributes from this XElement.

System.Xml.Linq.Extensions.Remove<T>(IEnumerable<T>)

https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.extensions.remove?view=netframework-4.7#System_Xml_Linq_Extensions_Remove__1_System_Collections_Generic_IEnumerable___0__

Removes every node in the source collection from its parent node.

System.Xml.Linq.XContainer.Add

https://stackoverflow.com/a/41181198/3782855

https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xcontainer.add?view=netframework-4.7#System_Xml_Linq_XContainer_Add_System_Object_

https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.parse?view=netframework-4.7#System_Xml_Linq_XElement_Parse_System_String_

  public void Add_ajaxControlToolkit()
{
string str = "<section name=\"ajaxControlToolkit\" type=\"AjaxControlToolkit.AjaxControlToolkitConfigSection, AjaxControlToolkit\" requirePermission=\"false\" />";
var parentElements = Element.Element("configSections");
parentElements?.Add(XElement.Parse(str));
}

编辑appSettings

 private void SaveSalt(string salt)
{
var value = $@"<add key=""CMSHashStringSalt"" value=""{salt}"" />";
var filePath = Path.Combine(websitePath, "web.config");
var rootElement = XElement.Load(filePath);
var parentElement = rootElement.Element("appSettings");
if (parentElement == null)
{
throw new Exception($"Can not find appSettings section in {filePath}");
} var targetElement = parentElement.Elements("add")
.FirstOrDefault(x => x.Attribute("key")?.Value == "CMSHashStringSalt");
if (targetElement == null)
{
parentElement.Add(XElement.Parse(value));
}
else
{
var attribute = targetElement.Attribute("value");
attribute?.SetValue(salt);
}
rootElement.Save(filePath);
}
  [Test]
public void XmlTest()
{
string xml = "<Record ID=\"135\" Key=\"CustomTableItemID\" /> <Record ID=\"23\" Key=\"CustomTableID\" />";
string root = $"Root{DateTime.Now:yyyyMMdd}";
xml = $"<{root}>{xml}</{root}>";
XElement element = XElement.Parse(xml);
var elementName = "Record";
var keyAttributeName = "Key";
var idAttributeName = "ID";
var keyValue1 = "CustomTableItemID";
var keyValue2 = "CustomTableID";
var node1 = element.Elements(elementName).FirstOrDefault(x => x.Attribute(keyAttributeName)?.Value == keyValue1)?.Attribute(idAttributeName)?.Value;
Console.WriteLine(node1);
var node2 = element.Elements(elementName).FirstOrDefault(x => x.Attribute(keyAttributeName)?.Value == keyValue2)?.Attribute(idAttributeName)?.Value;
Console.WriteLine(node2);
}

Basic Queries (LINQ to XML)的更多相关文章

  1. [原创]Linq to xml增删改查Linq 入门篇:分分钟带你遨游Linq to xml的世界

    本文原始作者博客 http://www.cnblogs.com/toutou Linq 入门篇(一):分分钟带你遨游linq to xml的世界 本文原创来自博客园 请叫我头头哥的博客, 请尊重版权, ...

  2. LINQ系列:LINQ to XML类

    LINQ to XML由System.Xml.Linq namespace实现,该namespace包含处理XML时用到的所有类.在使用LINQ to XML时需要添加System.Xml.Linq. ...

  3. LINQ系列:LINQ to XML操作

    LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...

  4. LINQ系列:LINQ to XML查询

    1. 读取XML文件 XDocument和XElement类都提供了导入XML文件的Load()方法,可以读取XML文件的内容,并转换为XDocument或XElement类的实例. 示例XML文件: ...

  5. Linq to Xml读取复杂xml(带命名空间)

    前言:xml的操作方式有多种,但要论使用频繁程度,博主用得最多的还是Linq to xml的方式,觉得它使用起来很方便,就用那么几个方法就能完成简单xml的读写.之前做的一个项目有一个很变态的需求:C ...

  6. c#操作xml文件(XmlDocument,XmlTextReader,Linq To Xml)

    主界面

  7. Linq对XML的简单操作

    前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...

  8. LINQ to XML 编程基础

    1.LINQ to XML类 以下的代码演示了如何使用LINQ to XML来快速创建一个xml: 隐藏行号 复制代码 ?创建 XML public static void CreateDocumen ...

  9. XML基础学习02<linq to xml>

    Linq to XML的理解 1:这是一种比较好的操作Xml的工具. àXDocument 文档 àXElement 元素 àXAttribute 属性 àXText 文本 2:这里还是和我们之前创建 ...

随机推荐

  1. 数列分块入门1~9 loj6277~6285

    hzwer的讲解 一 给出一个长为 \(n\) 的数列,以及 \(n\) 个操作,操作涉及区间加法,单点查值. #include <iostream> #include <cstdi ...

  2. 【Codeforces 1107D】Compression

    [链接] 我是链接,点我呀:) [题意] 题意 [题解] 先把所给的压缩形式的字符串转成二进制 然后对获得的01数组做一个前缀和(a[i][j]=以(i,j)为右下角,(1,1)为左上角的矩形内的数字 ...

  3. httpclient调用webservice接口的方法实例

    这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...

  4. 数据归一化Feature Scaling

    数据归一化Feature Scaling 当我们有如上样本时,若采用常规算欧拉距离的方法sqrt((5-1)2+(200-100)2), 样本间的距离被‘发现时间’所主导.尽管5是1的5倍,200只是 ...

  5. php-fpm.conf

    [global]pid = /usr/local/php/var/run/php-fpm.piderror_log = /usr/local/php/var/log/php-fpm.loglog_le ...

  6. CodeIgniter框架的缓存原理分解

    用缓存的目的:(手册上叙述如下,已经写得很清楚了) Codeigniter 支持缓存技术,以达到最快的速度. 尽管CI已经相当高效了,但是网页中的动态内容.主机的内存CPU 和数据库读取速度等因素直接 ...

  7. MySQL性能优化的21个最佳实践 和 mysql使用索引【转载】

    今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需要担心的事,而这更是我 们程序员需要去关注的事情.当我们去设计数据库表结构,对操作数 ...

  8. PHP 常见问题3

    1,Http 和 Https 的区别 第一:http 是超文本传输协议,信息是明文传输,https 是具有安全性的 ssl 加密传输协议 第二:http 和 https 使用的是完全不同的连接方式,端 ...

  9. Kibana 可视化监控报警插件 KAAE 的介绍与使用

    https://blog.csdn.net/phachon/article/details/53424631 https://blog.csdn.net/Dragon714/article/detai ...

  10. poj - 3686 The Windy's (KM算法)

    题意:n个订单和m个生产车间,每个订单在不同的车间生产所需要的时间不一样,并且每个订单只能在同一个车间中完成,直到这个车间完成这个订单就可以生产下一个订单.现在需要求完成n个订单的平均时间最少是多少. ...