How to get just the root element from Xelement - c#

I have the following XElement:
<Assembly name="3">
<Component name="2" />
</Assembly>
I would like to get just the root element. <Assembly name="3"> I cant see any method which suits for me.
XElement.????? I cant find XElement.Root;
Does any clue?

You can try this in VB.NET
Dim elm as XElment = XElement.Parse(<Assembly name="3">
<Component name="2" />
</Assembly>)
Dim strName as string
strName = elm.AncestorsAndSelf.First.Name
Code in C#
XElement elm = XElement.Parse("<Assembly name='3'><Component name='2' /></Assembly>");
string name =elm.AncestorsAndSelf().First().Name;

You can get the root element this way :
XDocument.Root
Here is an example of implementation :
XDocument doc = new XDocument(
new XComment("This is a comment."),
new XElement("Pubs",
new XElement("Book",
new XElement("Title", "Artifacts of Roman Civilization"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implements"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("This is another comment.")
);
Console.WriteLine(doc.Root.Name.ToString());
link : http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.root.aspx

You could call RemoveNodes on it... create a copy first if you need to preserve the original content for other reasons.
It's not really clear what you're trying to do with this. The element logically contains all its children - there's no concept of XElement.Root because an element "is itself". RemoveNodes will remove all the child nodes, but if you just want to get the name of the element, or its attributes, you can do that without changing the structure at all.

Copy the name & attributes to a new element;
var root = new XElement(el.Name, el.Attributes());

Related

Adding XMLElements

I'm trying to add entries to an existing specific xml doc that looks basically alike:
<body>
<setting>
<app name="notepad.exe" folder= "c:\windows\system32\" owner="peter"/>
<app name="calc.exe" folder= "c:\windows\system32\" age="4"/>
</setting>
</body>
The problem I have that I want to add multiple app entries, each width their own attributes, like owner or age etc. (ea not overwritting a single one).
I was thinking of
XDocument doc = new XDocument();
System.xml.XmlElement appnew = new system.Xml.XmlElement("<app name=\"write.exe\" folder="\c:\\windows\\system32\\\"")
Then later add the XmlElement to the sttings section however XMLElement can not be set like that, so I wonder how to add equal node names?
Try following
var doc =
new XDocument(
new XElement("body",
new XElement("setting",
new XElement("app", new XAttribute("age", "4")),
new XElement("app", new XAttribute("owner", "bitchiko"))
)));
In case you have existing XDocument and are trying to add new app element. Then try following
var doc= new XDocument(...);
var settingsXElement = doc.Descendants("setting").Single();
settingsXElement.Add(new XElement("app", new XAttribute("owner", "tchelidze")));

add elements multiple values in XDocument C#

I want to add a section with tag name called properties, and have one item value called property with multiple value, like node name, value
org xml file is like this
<testsuites>
<testsuite>
blah blah
</testsuite>
</testsuites>
After add, i want it show like this
<testsuites>
<testsuite>
<properties>
<property name="name" "value"="desirevalue"/>
</properties>
blah blah
</testsuite>
</testsuites>
The code that i wrote has some problems, it actually create two line of property, but i want them as one line. How should i update my code? Also seems last two line has problems. i get "object reference not set to an instance of an object" error
XDocument doc = XDocument.Load(fileOfReportInXML);
XElement root= new XElement("properties");
root.Add(new XElement("property", "name= node"));
root.Add(new XElement("property","value=desirevalue"));
doc.Element("testsuite").Add(root);
doc.Save(fileOfReportInXML);
Try following code:
//Load XML file
XDocument doc = XDocument.Load(fileOfReportInXML);
Edit: Add element to the first element of your xdocument
doc.Root.Elements("testsuite").First().Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));
if you want to add new elements to all your testsuite elements:
foreach (var element in doc.Root.Elements("testsuite"))
{
//Skip adding element if element already exists
if (element.HasElements && element.Element("properties") != null) continue;
element.Add(new XElement("properties", new XElement("property", new XAttribute("name", "name"), new XAttribute("value", "desirevalue"))));
}
Save the XML document
//Save XML file
doc.Save(fileOfReportInXML);

Replaceing a complete node in an existing xelement

I have an xElement data <a><item><item1/><item2/></item></a>
Need to replace item node with another node .
How can we achieve this?
I just need to replace item node with some other node say <b><b1/></b>
I want output as <a><b><b1/></b></a>
you could use ReplaceWith
xelementnode.ReplaceWith(new XElement(yournode));
Please find the below script, this is help you to replace the node
XElement xmlTree = new XElement("Students",
new XElement("Andrew", "Andrew Wilson"),
new XElement("Thomas", "Thomas Alwa"),
new XElement("Winston", "Winston GH"),
new XElement("Hary", "Hary Potter"),
new XElement("Jacky", "Jacky Elia")
);
XElement xel = xmlTree.Element("Winston");
xel.ReplaceWith(new XElement("Bill", "Bill Gate"));
Console.WriteLine(xmlTree);

How to get child and grandchild elements from XML element?

So, I have an XElement, that contains multiple child elements. I can successfully declare the XElement, and write it to a file:
Test.project:
<?xml version="1.0" encoding="utf-8"?>
<project>
<child>
<grand-child1>
<great-grand-child1>Hello There!</great-grand-child1>
<great-grand-child2>Hello World!</great-grand-child2>
</grand-child1>
<grand-child2>Testing 123...</grand-child2>
</child>
</project>
Then I'm trying to read from the file. I searched for ways to get child and grand-child nodes, and found I can use XElement.XPathSelectElement(). The problem is, Visual C# doesn't recognize XPathSelectElement as a method for an XElement. I've searched for usage examples for the method, and they all say to use XElement.XPathSelectElement.
For example, I tried:
x_el = new XElement("project",
new XElement("child",
new XElement("grand-child", "Hello World!")
);
string get_string = x_el.XPathSelectElement("child/grand-child");
...but XPathSelectElement is not recognized. What am I doing wrong?
You need to add System.Xml.XPath namespace as well
like
using System.Xml.XPath;
after that try below
x_el = new XElement("project",
new XElement("child",
new XElement("grand-child", "Hello World!")
));
// XPathSelectElement method return XElement not string , use var or XElement
XElement element = x_el.XPathSelectElement("child/grand-child");
string get_string = element.ToString()
Or
var get_string = x_el.XPathSelectElement("child/grand-child").ToString();

mixed up attributes and elements in xml

I need to create an xml the below structure.
<ipaddress> "10.10.10.10" </ipaddress>
<PipeId pid = "4598702C-691E">testvalue</PipeId> --how to display this?
<name> "testname" </name>
But I am really confused about the second line in the xml. How can it be displayed?
I tried below code..but don't know how to get the second line into xml..
new XElement("StartElement",
new XAttribute("TestAtt", "some & value"),
new XElement("ipaddress", "10.10.10.10"),
new XElement("name", "testname")));
If you're just trying to build that element, you want:
new XElement("PipeId", // Name of the element
new XAttribute("pid", "4598702C-691E"), // Attribute of the element
"testvalue") // Text content of the element

Categories

Resources