XML Element's element/attribute annotation in C# - c#

Is that possible to get an element's (child) element or an element's own attribute via xml annotation without phantom classes?
example current code snipet:
XML:
<root>
...
<epno type="1">12</epno>
...
</root>
C# classes:
[XmlRoot("root")]
class Root {
...
[XmlElement("epno")]
public Epno epno;
...
}
class Epno { //"Phantom" class
[XmlAttribute("type")]
public int type;
[XmlText]
public int epno;
}
What I want is to remove that Epno class and move those props into the Root class...
[XmlRoot("root")]
class Root {
...
[XmlElement("epno")]
[XmlAttribute("type")] // I need a solution for this...
public int type;
[XmlElement("epno")]
public int epno;
...
}
Also theres another place, where is a plus level, there I want to get an element's attribute, which is an another element... Than I want to get the element's element value.
For this an Xml example:
<root>
<rates>
<permanent votes="100">6.54</permanent>
<temprate votes="100">6.54</temprate>
</rates>
</root>
Here I want to put those values in to the root class, but in this case, there's need minimum 2 classes for parse it.
So, there's exist a way to deserialize these classes via annotation without these phantom classes and without writing my own xml parser?

There is no way to get "one child element and its attributes" of a root class and transform these into elements of its root class during XML Serialization by using only XML Serialization Attributes.
But, You can archieve desired result by:
Using XSLT Transformations
Implementing IXmlSerializable

I think what you are looking for is XmlDocument.
This does your second task:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml("<root><rates> <permanent votes = \"100\" > 6.54 </permanent> <temprate votes = \"100\" > 6.54 </temprate></rates> </root> ");
// find the nodes we are interested in
XmlNode Rates = xDoc.SelectSingleNode("//rates");
XmlNode Root = xDoc.SelectSingleNode("root");
// We can't modify a collection live so create a temporary list
List<XmlNode> TempList = new List<XmlNode>();
foreach (XmlNode Node in Rates.ChildNodes)
{
TempList.Add(Node);
}
// remove the nodes and their container node
foreach (XmlNode Node in TempList)
{
Node.ParentNode.RemoveChild(Node);
}
// Use this to remove the parent and children
// in one step
// Rates.ParentNode.RemoveChild(Rates);
// insert in desired location
foreach (XmlNode Node in TempList)
{
Root.AppendChild(Node);
}
// Hope this works!
xDoc.Save("C:\\test.xml");

Related

After I remove all the children of a ParentNode. The parentnode becomes null?

My goal is to remove all children from a parent so I end up with only the parent.
This is the OuterXml of Parent:
<?xml version="1.0"?>
<Parent xmlns="http://www.null.nl/zero">
<SpeedIndicator exists="True"/>
</Parent>
When I remove the child I get this in the OuterXml:
<Parent xmlns="http://www.null.nl/zero"></Parent>
I remove the children like this:
RemoveAllChildren(node.ParentNode);
public static string RemoveAllChildren(XmlNode xmlNode)
{
while (xmlNode.HasChildNodes)
{
xmlNode.RemoveChild(xmlNode.FirstChild);
}
return xmlNode.OuterXml;
}
But if I debug to check the new value of ParentNode.OuterXml. ParentNode has become null.
var whatgives = node.ParentNode.OuterXml;
I've tried RemoveAll on the ParentNode with the same result. What should I do to have the ParentNode I desire?
I can't reproduce the error. I ran a fiddle and it outputs the OuterXml as expected. I tried to remove the children nodes 3 different ways. Perhaps you need to check the contents of the node variable to make sure it contains what you expect before calling RemoveAllChildren. See fiddle:
using System;
using System.Xml;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
string xmlText = "<?xml version=\"1.0\"?><Parent xmlns=\"http://www.null.nl/zero\"><SpeedIndicator exists=\"True\"/></Parent>";
//Debugging
Console.WriteLine(xmlText);
//Load the XML string into an XmlDocument
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlText);
//Get the first child named "Parent"
XmlNode node = doc.GetElementsByTagName("Parent")[0];
//Remove all the children nodes.
node.RemoveAll();
//Output the remaining OuterXml
Console.WriteLine(node.OuterXml);
//Try again, reload the xml.
doc = new XmlDocument();
doc.LoadXml(xmlText);
//Get the first child named "Parent"
node = doc.GetElementsByTagName("Parent")[0];
//Different method to remove children.
while (node.HasChildNodes)
{
node.RemoveChild(node.FirstChild);
}
//Output the remaining OuterXml
Console.WriteLine(node.OuterXml);
//Third Try using function, reload the xml.
doc = new XmlDocument();
doc.LoadXml(xmlText);
//Get the first child named "Parent"
node = doc.GetElementsByTagName("Parent")[0];
//Output the returned string.
Console.WriteLine(RemoveAllChildren(node));
}
public static string RemoveAllChildren(XmlNode xmlNode)
{
while (xmlNode.HasChildNodes)
{
xmlNode.RemoveChild(xmlNode.FirstChild);
}
return xmlNode.OuterXml;
}
}

Modfiying Xml using C#

I have an xml
<PolicyHdr>
<PolicyHdrData>
<ID>123</ID>
</PolicyHdrData>
</PolicyHdr>
<Role>
<RoleData>
<DisplayFieldName>Payor</DisplayFieldName>
</RoleData>
</Role>
<PolicyCovHdr>
<PolicyCovHdrData>
<ID>000</ID>
<PolicyHdrID>123</PolicyHdrID>
</PolicyCovHdrData>
</PolicyCovHdr>
<Role>
<RoleData>
<DisplayFieldName>Insured</DisplayFieldName>
</RoleData>
</Role>
I need to modify this xml such that the PolicyCovHdr comes as child node of PolicyHDr where the ID node under PolicyHdr is equal to the PolicyHdrID under POlicyCovHDr.
Also the Role Nodes , whenever the DisplayFieldName is Payor it should be child of PolicyHdr and of the DisplayFieldName is Insure it should be the child node of PolicyCovHdr
So the final xml should look something like this:-
<PolicyHdr>
<PolicyHdrData>
<ID>123</ID>
<Role>
<RoleData>
<DisplayFieldName>Payor</DisplayFieldName>
</RoleData>
</Role>
</PolicyHdrData>
<PolicyCovHdr>
<PolicyCovHdrData>
<ID>000</ID>
<PolicyHdrID>123</PolicyHdrID>
<Role>
<RoleData>
<DisplayFieldName>Insured</DisplayFieldName>
</RoleData>
</Role>
</PolicyCovHdrData>
</PolicyCovHdr>
</PolicyHdr>
Could someone help me with some logic which I could use to achieve this xml
Hi sorry I forgot to add my code changes here
string xml1 = "<xml><PolicyHdr><PolicyHdrData><ID>123</ID></PolicyHdrData></PolicyHdr><Role><RoleData><DisplayFieldName>Payor</DisplayFieldName></RoleData></Role><PolicyCovHdr><PolicyCovHdrData><ID>000</ID><PolicyHdrID>123</PolicyHdrID></PolicyCovHdrData></PolicyCovHdr><Role><RoleData><DisplayFieldName>Insured</DisplayFieldName></RoleData></Role></xml>";
XmlDocument test = new XmlDocument();
test.LoadXml(xml1);
XmlNodeList polList = test.SelectNodes("//PolicyHdr/PolicyHdrData");
foreach (XmlNode xn in polList)
{
XmlNode polNode = xn.SelectSingleNode("//PolicyHdr/PolicyHdrData/ID");
XmlNodeList polCovNodeList = test.SelectNodes("//PolicyCovHdr/PolicyCovHdrData");
foreach (XmlNode yn in polCovNodeList)
{
XmlNode polCovPolNode = yn.SelectSingleNode("//PolicyCovHdr/PolicyCovHdrData/PolicyHdrID");
if(polNode.InnerText.ToString().Equals(polCovPolNode.InnerText.ToString()))
{
xn.AppendChild(yn);
}
}
XmlNodeList polRoleList = test.SelectNodes("//Role/RoleData");
foreach (XmlNode zn in polRoleList )
{
XmlNode RoleNode = zn.SelectSingleNode("//Role/RoleData/DisplayFieldName");
if(RoleNode.InnerText.ToString().Equals("Payor"))
{
xn.AppendChild(zn);
}
//Console.WriteLine(RoleNode.InnerText.ToString());
}
Console.WriteLine(xn.OuterXml.ToString());
}
The problem right now I am facing is the complexity is (n^2) and adding the Role node as child to PolicyCovHdr when DisplayFieldName = Insured.
Right now the output looks like this
<PolicyHdrData><ID>123</ID><PolicyCovHdrData><ID>000</ID><PolicyHdrID>123</PolicyHdrID></PolicyCovHdrData><RoleData><DisplayFieldName>Payor</DisplayFieldName></RoleData></PolicyHdrData>
I am still thinking of how to add the Role with DisplayFieldname as Insured as well because of the complexity is already very high
I think that you should use XML Serialization/Deserialization. You can look for example to this question: C# Xml Serialization & Deserialization
At first you can create an object with structure of your input XML, than use XML Deserializer to load the data from XML to this object. After that you can work with the instance of an object and ad some conditions to your code which you need.
You can create another objects which will be representing output XML (depends on the structure as you wrote about it) and in if/else code filling the object with the data you need. Structure of XML will be represented by the structure of the object. Finally you can use XML Serializer to create your XML.
There could probably be better solution, but that should also work.

How add,edit and delete node by line in xml

I have string XML. I loaded to XmlDocument. How can I add, edit and delete by simplest method by line, because I know only line which I should edit. It's better work wih XML like with string, or better work with XmlDocuments?
using System;
using System.Xml;
namespace testXMl
{
class Program
{
static void Main(string[] args)
{
string xml="<?xml version=\"1.0\"?>\r\n<application>\r\n<features>\r\n<test key=\"some_key\">\r\n</features>\r\n</application>";
XmlDocument xm = new XmlDocument();
xm.LoadXml(xml);
//Edit third line
//xm[3].EditName(featuresNew);
//xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<featuresNew>\r\n<test key=\"some_key\">\r\n</featuresNew>\r\n</application>"
//Add fourth line the Node
//xm[4].AddNode("FeatureNext");
//xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<FeatureNext>\r\n<FeatureNext>\r\n</features2>\r\n<test key=\"some_key\">\r\n</features>\r\n</application>"
//Delete sixth line
//xm[6].DeleteNode;
//xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<FeatureNext>\r\n<FeatureNext>\r\n</features2>\r\n</features>\r\n</application>"
}
}
}
Thanks, in advance.
You should always work with XDocument/XmlDocument objects. A key knowledge is the XPath query language.
This a quick XML crash course. Run with debugger and inspect the XML variable as you move on.
var xml = new XmlDocument();
xml.LoadXml(#"<?xml version='1.0'?>
<application>
<features>
<test key='some_key' />
</features>
</application>");
// Select an element to work with; I prefer to work with XmlElement instead of XmlNode
var test = (XmlElement) xml.SelectSingleNode("//test");
test.InnerText = "another";
test.SetAttribute("sample", "value");
var attr = test.GetAttribute("xyz"); // Works, even if that attribute doesn't exists
// Create a new element: you'll need to point where you should add a child element
var newElement = xml.CreateElement("newElement");
xml.SelectSingleNode("/application/features").AppendChild(newElement);
// You can also select elements by its position;
// in this example, take the second element inside "features" regardless its name
var delete = xml.SelectSingleNode("/application/features/*[2]");
// Trick part: if you found the element, navigate to its parent and remove the child
if (delete != null)
delete.ParentNode.RemoveChild(delete);

Change Value of the last Attribute in an XML c#

I was working on a bunch of XMLs that all share an attribute that contains the string "name" in them. The following code selects the attribute with string "name" in it and assign a new value to it.
public void updateXmlFile(string strFileName)
{
try
{
//Load the Document
XmlDocument doc = new XmlDocument();
doc.Load(strFileName);
//Set the changed Value
string newValue = GetUniqueKey();
//Select all nodes in the XML then choose from them
//the first node that contain string "name" in it
XmlNodeList list = doc.SelectNodes("//#*");
XmlNode filteredNode = list.Cast<XmlNode>()
.First(item => item.Name.ToLower().Contains("name"));
//Assign the newValue to the value of the node
filteredNode.Value = newValue;
doc.Save(strFileName);
}
catch (XmlException xex) { Console.WriteLine(xex); }
}
Now a new XMLs were added that dosen't have the string "name" in them, so instead of modifying the attribute with string "name" in it I decided to simply modify the last attribute no matter what it was (not the first)
Can anybody tell me how to do that?
EDIT
Here is an example of my XML
<?xml version="1.0" encoding="utf-8"?>
<CO_CallSignLists Version="24" ModDttm="2010-09-13T06:45:38.873" ModUser="EUADEV\SARE100" ModuleOwner="EUADEVS06\SS2008" CreateDttm="2009-11-05T10:19:31.583" CreateUser="EUADEV\A003893">
<CoCallSignLists DataclassId="E3FC5E2D-FE84-492D-AD94-3ACCED870714" EntityId="E3FC5E2D-FE84-492D-AD94-3ACCED870714" MissionID="4CF71AB2-0D92-DE11-B5D1-000C46F3773D" BroadcastType="S" DeputyInSpecialList="1" SunSpots="1537634cb70c6d80">
<CoCallSigns EntityId="DEBF1DDB-3C92-DE11-A280-000C46F377C4" CmdID="C45F3EF1-1292-DE11-B5D1-000C46F3773D" ModuleID="6CB497F3-AD63-43F1-ACAE-2C5C3B1D7F61" ListType="HS" Name="Reda Sabassi" Broadcast="INTO" PhysicalAddress="37" IsGS="1" HCId="0" CommonGeoPos="1" GeoLat="0.0000000" GeoLong="0.0000000">
<CoRadios EntityId="E1BF1DDB-3C92-DE11-A280-000C46F377C4" RadioType="HF" />
</CoCallSigns>
</CoCallSignLists>
</CO_CallSignLists>
#Alex: You notice that the "SunSpots" attribute (last attribute in the first child element) is successfully changed. But now when I wanna load the XML back into the DB it gives me an error
Here is the modified code
public void updateXmlFile(string strFileName)
{
try
{
XDocument doc = XDocument.Load(strFileName);
XAttribute l_attr_1 = (doc.Elements().First().Elements().First().Attributes().Last());
l_attr_1.Value = GetUniqueKey();
Console.WriteLine("Name: {0} Value:{1}", l_attr_1.Name, l_attr_1.Value);
doc.Save(strFileName);
}
catch (XmlException xex) { Console.WriteLine(xex); }
}
I was thinking of making an if statment which checks if the XML has an attribute that contains string "name" in it (since most of my XMLs has an attribute that contains name in them) if it does then change the attribute's value if not look for the last attribute and change it.. not the best solution but just throwing it out there
Then definitely use Linq to XML.
Example:
using System.Xml.Linq;
string xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Commands Version=""439"" CreateUser=""Reda"">
<CmCommands DataclassId=""57067ca8-ef96-4d2e-a085-6bd7e8b24126"" OrderName = ""Tea"" Remark=""Black"">
<CmExecutions EntityId=""A9A5B0F2-6AB4-4619-9106-B0F85F86EE01"" Lock=""n"" />
</CmCommands>
</Commands>";
XDocument x = XDocument.Parse(xml);
Debug.Print(x.Elements().First().Elements().First().Attributes().Last().Value);
// Commands ^ CmCommands ^ Remark ^
That is, word for word, the last attribute of the first child of the first element.
You can also query for element/attribute names, like:
Debug.Print(x.Descendants(XName.Get("CmCommands", "")).First().Attribute(XName.Get("Remark", "")).Value);
And of course you can use all of the Linq goodness like Where, Select, Any, All etc.
Note: replace XDocument.Parse with XDocument.Load if appropriate etc.
I've not tested this but you should be able to do all of this in the XPath expression. Something like this:
//#*[contains(node-name(.), 'name')][last()]
This will return only the last attribute with the string name anywhere in its name.
If you only want the last attribute, irrespective of it's name, use this:
//#*[last()]
Look at class XmlAttributeCollection. You can get this collection by reading property Attributes of XmlNode. Just get the last by index.
Instead of .First(), use an extension method like this:
public static T LastOrDefault<T>(this IEnumerable<T> list)
{
T val = null;
foreach(T item in list)
{
val = item;
}
return val;
}

xmldoc.Childnodes.item() question

I decided to try out the tutorial on this website
http://www.csharphelp.com/2006/05/creating-a-xml-document-with-c/
Here's my code, which is more or less the same but a bit easier to read
using System;
using System.Xml;
public class Mainclass
{
public static void Main()
{
XmlDocument XmlDoc = new XmlDocument();
XmlDocument xmldoc;
XmlNode node1;
node1 = XmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
XmlDoc.AppendChild(node1);
XmlElement element1;
element1 = XmlDoc.CreateElement("", "ROOT", "");
XmlText text1;
text1 = XmlDoc.CreateTextNode("this is the text of the root element");
element1.AppendChild(text1);
// appends the text specified above to the element1
XmlDoc.AppendChild(element1);
// another element
XmlElement element2;
element2 = XmlDoc.CreateElement("", "AnotherElement", "");
XmlText text2;
text2 = XmlDoc.CreateTextNode("This is the text of this element");
element2.AppendChild(text2);
XmlDoc.ChildNodes.Item(1).AppendChild(element2);
}
}
So far, I'm liking XmlDocument, but I can't figure out how this line works
XmlDoc.ChildNodes.Item(1).AppendChild(element2);
Specifically, the Item() part of it
according to MSDN...
//
// Summary:
// Retrieves a node at the given index.
//
// Parameters:
// index:
// Zero-based index into the list of nodes.
//
// Returns:
// The System.Xml.XmlNode in the collection. If index is greater than or equal
// to the number of nodes in the list, this returns null.
However, I'm still not really sure what "index" refers to, or what Item() does. Does it move down the tree or down a branch?
Also, when I was looking at it, I thought it would end up like this
what I thought would happen:
<?xml version="1.0"?>
<ROOT>this is the text of the root element</ROOT>
<AnotherElement>This is the text of this element</AnotherElement>
but it ended up like this
Actual output
<?xml version="1.0"?>
<ROOT>this is the text of the root element
<AnotherElement>This is the text of this element</AnotherElement>
</ROOT>
(formatting added)
The ChildNodes property returns the XmlNodeList of immediate children of what you call it on. Item then finds the nth member of that list. It won't recurse into grand-children etc. In particular, I believe in this case Item(0) would return the XML declaration, and Item(1) returns the root element. A nicer way of expressing "get to the root element" would be to use XmlDocument.DocumentElement.
Note that your "expected" output wouldn't even be valid XML - an XML document can only have one root element.
To be honest, this isn't a terribly nice use of it - and in particular I would recommend using LINQ to XML rather than XmlDocument if you possibly can. It's not particularly clear what you're trying to achieve with the code you've given, but it would almost certainly be much simpler in LINQ to XML.

Categories

Resources