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:这里还是和我们之前创建 ...
随机推荐
- 【转】Entity Framework6 with Oracle(可实现code first)
Oracle 已在2014年底提供对EF6的支持.以前只支持到EF5.EF6有很多有用的功能 值得升级.这里介绍下如何支持Oracle 一.Oracle 对.net支持的一些基础知识了解介绍. 1 ...
- MySQL报错The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents
参考资料:https://blog.csdn.net/qq_37630354/article/details/82814330 在property里加上最后这个参数即可
- jmespath库解析json
在测试过程中,经常会去JSON中的某个值,jmespath可以是除了jsonpath的另外一种选择. 下面通过几个例子来说明jmespath在python的使用 jmespath python安装 非 ...
- Python工程师面试题目
1.请尽可能列举python列表的成员方法,并给出一下列表操作的答案: len() 返回列表中的元素数量. max() 返回列表中的最大元素.最大元素的判断依据是列表中的对象类型.数字列表中的最大元素 ...
- 大数据学习——修改主机名和ip的映射关系
vi /etc/hosts 192.168.1.101 itcast
- 一个jboss启动shell脚本
脚本1: #!/bin/sh # paulo@evencom.com.br #JBOSS_HOME JBOSS_HOME="/opt/app/jboss-eap-6.3" JAVA ...
- CodeForces 556 --Case of Fake Numbers
B. Case of Fake Numbers time limit per test 2 seconds memory limit per test 256 megabytes input stan ...
- 『NYIST』第八届河南省ACM竞赛训练赛[正式赛一]CF-236B. Easy Number Challenge
B. Easy Number Challenge time limit per test 2 seconds memory limit per test 256 megabytes input sta ...
- [Go]程序实体
Go语言中的程序实体包括变量.常量.函数.结构体.接口 1.常见声明变量的方式 package main import ( "flag" "fmt" ) fun ...
- 【HDOJ6342】Expression in Memories(模拟)
题意: 给定一个由0123456789+* ?组成的表达式,其中?可以被改为任意其它字符,问修改问号后是否有方案使得表达式合法 len<=5e2,sumlen<=1e5 思路: #incl ...