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
- Querying XML Trees (C#)
- https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/programming-guide-linq-to-xml
实战
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 一般用不到这个,都是用另外一个
Removes nodes and attributes from this XElement.
System.Xml.Linq.Extensions.Remove<T>(IEnumerable<T>)
Removes every node in the source collection from its parent node.
System.Xml.Linq.XContainer.Add
https://stackoverflow.com/a/41181198/3782855
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)的更多相关文章
- [原创]Linq to xml增删改查Linq 入门篇:分分钟带你遨游Linq to xml的世界
本文原始作者博客 http://www.cnblogs.com/toutou Linq 入门篇(一):分分钟带你遨游linq to xml的世界 本文原创来自博客园 请叫我头头哥的博客, 请尊重版权, ...
- LINQ系列:LINQ to XML类
LINQ to XML由System.Xml.Linq namespace实现,该namespace包含处理XML时用到的所有类.在使用LINQ to XML时需要添加System.Xml.Linq. ...
- LINQ系列:LINQ to XML操作
LINQ to XML操作XML文件的方法,如创建XML文件.添加新的元素到XML文件中.修改XML文件中的元素.删除XML文件中的元素等. 1. 创建XML文件 string xmlFilePath ...
- LINQ系列:LINQ to XML查询
1. 读取XML文件 XDocument和XElement类都提供了导入XML文件的Load()方法,可以读取XML文件的内容,并转换为XDocument或XElement类的实例. 示例XML文件: ...
- Linq to Xml读取复杂xml(带命名空间)
前言:xml的操作方式有多种,但要论使用频繁程度,博主用得最多的还是Linq to xml的方式,觉得它使用起来很方便,就用那么几个方法就能完成简单xml的读写.之前做的一个项目有一个很变态的需求:C ...
- c#操作xml文件(XmlDocument,XmlTextReader,Linq To Xml)
主界面
- Linq对XML的简单操作
前两章介绍了关于Linq创建.解析SOAP格式的XML,在实际运用中,可能会对xml进行一些其它的操作,比如基础的增删该查,而操作对象首先需要获取对象,针对于DOM操作来说,Linq确实方便了不少,如 ...
- LINQ to XML 编程基础
1.LINQ to XML类 以下的代码演示了如何使用LINQ to XML来快速创建一个xml: 隐藏行号 复制代码 ?创建 XML public static void CreateDocumen ...
- XML基础学习02<linq to xml>
Linq to XML的理解 1:这是一种比较好的操作Xml的工具. àXDocument 文档 àXElement 元素 àXAttribute 属性 àXText 文本 2:这里还是和我们之前创建 ...
随机推荐
- 大数据学习——JAVA采集程序
1 需求 从外部购买数据,数据提供方会实时将数据推送到6台FTP服务器上,我方部署6台接口采集机来对接采集数据,并上传到HDFS中 提供商在FTP上生成数据的规则是以小时为单位建立文件夹(2016-0 ...
- XV6第一个进程
第一个进程 本章通过第一个进程的创建来解释 xv6 是如何开始运行的,让我们得以一窥 xv6 提供的各个抽象是如何实现和交互的.xv6 尽量复用了普通操作的代码来建立第一个进程,避免单独为其撰写代码. ...
- Go变量定义学习
package main import ( "fmt" ) //变量定义: //使用var关键字或:=定义变量 //可放在函数内,或直接放在包内 //使用var()集中定义 //函 ...
- [USACO10FEB]慢下来Slowing down
线段树 树的dfs序 来自 洛谷 P1982 的翻译 by GeneralLiu 来自 jzyz 的翻译 %mzx 线段树 dfs序 数据结构的应用 “数据结构 是先有需求 再有应用” ...
- [luoguP2577] [ZJOI2005]午餐(DP)
传送门 显然吃饭时间越长的人排在前面越好,所以先排序. f[i][j]表示前i个人,A队的打饭时间为j的最优解,每个人只有两种选择,去A队或是去B队. #include <cstdio> ...
- C# 通过HTTP代理访问Socket来获取邮件
C# 通过HTTP代理访问Socket来获取邮件 关键穿透代理的代码(通过HTTP代理获取TcpClent) public class ClientHelper { public static Tcp ...
- K/3Cloud二次开发基于WebDev附加进程调试
大部分人在进行K/3cloud二次开发插件的调试时,选择的是附加IIS进程w3wp调试,本文给大家介绍一下基于WebDev附加进程调试,不用重启iis. 步骤如下: 1)拷贝K/3cloud产品安装目 ...
- 【BZOJ1834】network 网络扩容(最大流,费用流)
题意:给定一张有向图,每条边都有一个容量C和一个扩容费用W.这里扩容费用是指将容量扩大1所需的费用. 求: 1. 在不扩容的情况下,1到N的最大流: 2. 将1到N的最大流增加K所需的最小扩容费用. ...
- HDU 6070 (线段树)(统计颜色)
HDU 6070 Partition Problem : 给一段长度为n的序列,要求找出一段区间,使得这段区间的数字种类除以区间长度最小.输出最后的答案即可.(n <= 60000)(9s时限) ...
- 关于Linux内核学习的一点点总结
关于Linux内核学习的一点点总结 关键词:Linux, 操作系统,内核 博客列表 由反汇编C程序来理解计算机是如何工作的 通过分析一个简化版时间片轮转多道程序内核代码来认识操作系统中的进程调度 通过 ...