I have following xml structure I want to update it through c#
How to update it
Is it possible to update through Linq if yes then how to do it?
I want to add UnitTest, TestList, TestEntry and UnitTestResults elements through code.
`
<?xml version="1.0" encoding="UTF-8"?>
<TestRun id="1" xmlns="http://microsoft.com/schemas">
<TestDefinitions>
<UnitTest name="Test1" id="T1">
<Execution id="E1" />
</UnitTest>
<UnitTest name="Test2" id="T2">
<Execution id="E2" />
</UnitTest>
:
:
</TestDefinitions>
<TestLists>
<TestList name="List1" id="L1" />
<TestList name="List2" id="L2" />
:
:
</TestLists>
<TestEntries>
<TestEntry testId="T1" executionId="E1" testListId="L1" />
<TestEntry testId="T2" executionId="E2" testListId="L2" />
:
:
</TestEntries>
<Results>
<UnitTestResult executionId="E1" testId="T1" testName="Test1" >
<Output>
<ErrorInfo>
<Message>Hi</Message>
</ErrorInfo>
</Output>
</UnitTestResult>
</Results>
<Results>
:
:
</TestRun>
`
Yes, it is possible by LINQ. This is the example code to add new
UnitTestelement:To add the element you must create the
XElementobject and pass to its constructor the name of the new element and all its stuff like child elements, attributes (through a comma). Then you must specify where you want to add new element: by going from the Root element through the XML three (like in this example) or by query.You can find needed element by LINQ query. Next example shows how to get all
TestEntriesfrom theTestListwith idL1:Result objects from this query have anonymous type with useful properties. If you want work with
XElementobjects, simply changeselect new ...toselect e.If you want update the value of the element, find it (look above) and call the
SetValue()method.If you working with namespaces (like you file) you must create
XNamespaceobject with needed value and concatenate it with all elements’ names that you need.To save your changes to the xml file on dist, call
Save()method.LINQ to XML Overview in MSDN