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); }