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:这里还是和我们之前创建 ...
随机推荐
- [转]Selenium-Webdriver系列Python版教程(1)————快速开始
elenium的历史,selenium2与WebDriver的关系本文就不讲了,想了解的同学们百度一下就可以Ok. 本系列教程是以Selenium-WebDriver的Python版本,首先从 ...
- Ubuntu 配置Apache虚拟目录
http://blog.csdn.net/spring21st/article/details/6589300 Ubuntu 配置Apache虚拟目录 http://blog.csdn.net/spr ...
- sql语句中嵌套2层循环
declare @year intdeclare @month intset @year=2008 while(@year<=2011)beginset @month=1while(@month ...
- C 的指针和内存泄漏
引言 对于任何使用 C 语言的人,如果问他们 C 语言的最大烦恼是什么,其中许多人可能会回答说是指针和内存泄漏.这些的确是消耗了开发人员大多数调试时间的事项.指针和内存泄漏对某些开发人员来说似乎令人畏 ...
- Codeforces 892 B.Wrath
B. Wrath time limit per test 2 seconds memory limit per test 256 megabytes input standard input outp ...
- visual studio用"查找替换"来删掉源代码中所有//方式的纯注释和空行
visual studio用"查找替换"来删掉源代码中所有//方式的纯注释和空行 注意:包括/// <summary>这样的XML注释也都删掉了. 步骤1/2(删除注释 ...
- APP后端处理视频的方案
在当前的app应用中,到处都能看到视频的身影,例如,在社交类的app上,用户可以拍摄属于自己的小视频,并发布到相应得栏目,增加和好友们互动的机会. 后台常见的视频处理有以下几种: · ...
- Codeforces 618C(计算几何)
C. Constellation time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...
- git修改commit message及vi编辑器的简单使用
1.修改commit信息 git commit --amend 2.进入vi编辑器修改 ‘i’进入insert模式,输入文字: ‘esc’回到命令模式,删除文字,移动光标: ‘:’进入底行模式,‘wq ...
- React学习及实例开发(三)——用react-router跳转页面
本文基于React v16.4.1 初学react,有理解不对的地方,欢迎批评指正^_^ 一.定义路由 1.安装react-router npm install react-router@ --sav ...