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:这里还是和我们之前创建 ...
随机推荐
- Vmware改成bridge方式联网
1.在使用桥接之前,先在真机的'更改适配器设置中'禁用vmnet1和vmnet8 2.在VMware中定义一个桥接器 3.设置这个Linux虚拟机使用前一个步骤定义的桥接器--进入桥接器选择界面 4. ...
- 比较spring cloud和dubbo,各自的优缺点是什么
dubbo由于是二进制的传输,占用带宽会更少springCloud是http协议传输,带宽会比较多,同时使用http协议一般会使用JSON报文,消耗会更大 dubbo的开发难度较大,原因是dubbo的 ...
- HTTP API 自动化测试从手工测试到平台的演变
不管是 Web 系统,还是移动 APP,前后端逻辑的分离设计已经是常态化,相互之间通过 API 调用进行数据交互.在基于 API 约定的开发模式下,如何加速请求 / 响应的 API 测试,让研发人员及 ...
- 洛谷P2870 - [USACO07DEC]最佳牛线Best Cow Line
Portal Description 给出一个字符串\(s(|s|\leq3\times10^4)\),每次从\(s\)的开头或结尾取出一个字符接在新字符串\(s'\)的末尾.求字典序最小的\(s'\ ...
- 【记录】新建Cordova项目出现ios-deploy找不到的问题
按老流程 Cordova create helloApp Cordova platform add ios 之前一般这种操作之后就能有执行的iOS目录了,像这样 然后 Cordova build ...
- 解决Genymotion运行Android 5.0一直卡在开机界面
在一些机器,启动genymotion 的android5.0版模拟器时,会卡在启动界面,一直启动不了. 这是因为要求的开启虚拟选项没有打开,在第一次启动时,会有提示,但可能大家没有注意(我也没注意到, ...
- SkyWalking 分布式追踪系统
随着微服务架构的流行,一些微服务架构下的问题也会越来越突出,比如一个请求会涉及多个服务,而服务本身可能也会依赖其他服务,整个请求路径就构成了一个网状的调用链,而在整个调用链中一旦某个节点发生异常,整个 ...
- 骑士精神 (codevs 2449)
题目描述 Description 在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位.在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标 ...
- wordpress网站后台打开速度很慢解决方法?
今天就和朋友们分享下,wordpress网站后台最近打开速度很慢的原因及解决方法.推荐第三种方法 方法/步骤 1.安装插件:在插件中搜索 Disable Google Fonts,选择安装,然后启 ...
- React Native资料汇总
React Native 官方文档中文版翻译 http://wiki.jikexueyuan.com/project/react-native/homepage.html REACT NATIVE开发 ...