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); }
作者:Chuck Lu GitHub |
分类:
linq to xml
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-09-25 CodeWars for JavaScript
2017-09-25 JQuery
2017-09-25 Getting started with Kentico
2015-09-25 Bex64
2015-09-25 IPv6 tutorial – Part 8: Special addresses
2015-09-25 IPv6 tutorial – Part 7: Zone ID and unique local IPv6 unicast addresses
2015-09-25 ipconfig命令