Delete xElement by xAttribute value - c#

I have the following xml document:
<?xml version="1.0" encoding="utf-8"?>
<Categories>
<title>
<Type name="James">
<Field name="ref" value="79" />
<Field name="titleref" value="55" />
</Type>
</title>
</Categories>
I want to delete all of 'title' if the textBox1 text matches
I have the following, I know it doesn't work, but I wanted to see if you can see my logic.
xmldoc.Root.Elements().Where(x => x.Element("Type")).Where (x => x.Attribute("name").Value.Equals(textBox1.Text)).Select(x => x).Single().Remove();
Any help would be great
Thanks

You can use XPath (System.Xml.XPath)
xmldoc.XPathSelectElements(String.Format("//Type[#name='{0}']", textBox1.Text))
.Remove();

xmldoc.Root.Descendants( "Type" )
.Where( x => x.Attribute( "name" ).Value == textBox1.Text )
.Remove();

Related

Linq to XML delete parent node

I'm trying to delete a parent from a element in XML.
My XML:
<root>
<Element1 ManagementID="10" />
<Users>
<UserID ManagementID="10">
<Identification IDValue="1" />
<!-- More elements Here -->
</UserID>
</Users>
<!-- More Users elements Here -->
I find my user my its IDValue:
XElement user = (from el in document.Root.Elements("Users").Elements("UserID ").Elements("Identification")
where (string)el.Attribute("IDValue") == myID
select el).FirstOrDefault();
Now, I would like to remove all the user.Parent.Parent
I mean delete the element:
<Users>
<UserID ManagementID="10">
<Identification IDValue="1" />
<!-- More elements Here -->
</UserID>
</Users>
** I'll have many Users elements, that's why first I look for the identification IDValue
I found the solution for who needs it:
I already had the node from my linq so
user.Parent.Parent.Remove()
var user = document.Root
.XPathSelectElements("//UserId")
.FirstOrDefault(userId => userId.Element("Identification").Attribute(XName.Get("IDValue")).Value == myID);
Try this :
List<XElement> users = document.Descendants("Users")
.Where(user => user.Elements("Identification")
.Where(el => (string)el.Attribute("IDValue") != myID)
.Any()).ToList();
XElement element1 = document.Descendants("Element1").FirstOrDefault();
element1.ReplaceNodes(users);

C#: Check particular attribute key-value pair is present using linq

I want to check whether a particular attribute key-value pair is present using linq.
I am using following code to check:
bool keyPresent = xDocument.Element("noSqlDb").Element("elements").Elements("key")
.Where(el => el.Attribute("id").Equals(key.ToString()))
.Any();
My XML looks like below:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<noSqlDb>
<keytype>System.Int32</keytype>
<payloadtype>a</payloadtype>
<elements>
<key id="1">
<name>element</name>
<descr>test element</descr>
<timestamp>2015-10-02T23:54:07.6562371-04:00</timestamp>
<children>
<item>1</item>
<item>2</item>
<item>3</item>
</children>
<payload>
<item>CSE681</item>
<item>SMA</item>
<item>C#.net</item>
</payload>
</key>
</elements>
</noSqlDb>
You could simply use Xpath to try to find the element.
bool keyPresent = xDocument.XPathSelectElement(String.Format("//key[#id={0}]", key)) != null;
..or using LINQ
bool keyPresent = xDocument.Descendants()
.Any(e => e.Name == "key" && e.Attributes()
.Any(a => a.Name == "id" && a.Value == key.ToString()));

c# sort XElement, with comments

I have an XElement that represents following xml:
<Node>
<Child id="1" /><!-- Comment 1 -->
<Child id="3" /><!-- Comment 3 -->
<Child id="2" /><!-- Comment 2 -->
</Node>
How can I sort the children of Node so that the XElement.ToString() method returns the following?
The comments and text behind the child must be moved along.
<Node>
<Child id="1" /><!-- Comment 1 -->
<Child id="2" /><!-- Comment 2 -->
<Child id="3" /><!-- Comment 3 -->
</Node>
Assuming each element is succeeded by the corresponding comment, try the following:
var xDoc = XDocument.Parse(/* your xml */);
var reordered = xDoc.Root
.Elements("Child")
.Select(el => new {
Element = el,
Comments = el.NodesAfterSelf()
.TakeWhile(n => n.NodeType == XmlNodeType.Comment)
})
.OrderBy(pair => (int)pair.Element.Attribute("id"))
.SelectMany(pair => new [] { pair.Element }.Concat(pair.Comments));
xDoc.Root.ReplaceAll(reordered);
EDIT: edited to allow any (incl. 0) number of comments per element; whitespace was already handled.

Traversing through xml file

I have XML like this.
<?xml version="1.0" encoding="utf-8" ?>
<config>
<atag>
<element1 att="value" />
<element2 att="othervalue"/>
</atag>
<othertag>
<element1 att="value" />
<element2 att="othervalue"/>
</othertag>
</config>
I want to traverse through the file and find "element1" tag and raplce it with "abc" tag.
Please help. Thank You in advance
In the same file I want to store att value in an array first then raplace the tag name to "abc" . Please help me out
var xml = XDocument.Load(fileName);
foreach (var e in xml.Root.Elements().SelectMany(x => x.Elements("element1")))
{
e.Name = "abc";
}
xml.Save(fileName);

How to use SetElementValue on XDocument

This is the sample of my xml
<?xml version="1.0"?>
<SearchHistory>
<Search>
<title>Text 1</title>
<count>0</count>
</Search>
<Search>
<title>Text 2</title>
<count>0</count>
</Search>
</SearchHistory>
And I want to change the value of count of Text 1
this is what i tried:
xdoc.Descendants("Search")
.Where(x => x.Element("title").Value == tbSearch.Text)
.Single().SetElementValue("count", curCount);
You have to Save the XDocument when you have made changes
xDoc.Save(fileName);
xdoc.Descendants("Search")
.Where(x => x.Element("title").Value == tbSearch.Text)
.Single()
.Descendants("count")
.Single()
.Value = "1";

Categories

Resources