Tuesday, 11 May 2021

create xml using model class c#

 public string CreateXML(Object p)

{

XmlDocument xmlDoc = new XmlDocument();   //Represents an XML document, 

  // Initializes a new instance of the XmlDocument class.          

XmlSerializer xmlSerializer = new XmlSerializer(p.GetType());

 Creates a stream whose backing store is memory. 

using (MemoryStream xmlStream = new MemoryStream())

{

xmlSerializer.Serialize(xmlStream, p);

xmlStream.Position = 0;

//Loads the XML document from the specified string.

xmlDoc.Load(xmlStream);

return xmlDoc.InnerXml;

}

}

//call in any method to grab data

string strView = CreateXML(p);

//another xml example with model class

XmlDocument doc = new XmlDocument();

XmlNode docnode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

doc.AppendChild(docnode);

XmlNode usersNode = doc.CreateElement("CreateOrderTest");

doc.AppendChild(usersNode);

XmlNode userNode = doc.CreateElement("User");

XmlAttribute userAttribute = doc.CreateAttribute("Id");

userAttribute.Value = "1";

usersNode.AppendChild(userNode);

XmlNode nameNode = doc.CreateElement("Name");

nameNode.AppendChild(doc.CreateTextNode("frank"));

userNode.AppendChild(nameNode);

XmlNode addressNode = doc.CreateElement("Adrees");

addressNode.AppendChild(doc.CreateTextNode("1 Main St."));

userNode.AppendChild(addressNode);

var XMLString = doc.InnerXml;

localhost.webservices test = new localhost.webservices();

var res = test.TextXML(XMLString);

return view();


No comments:

Post a Comment

7 Common mistakes in Dot Net — You can avoid

  There are many common mistakes made during .NET (ASP.NET, .NET Core) development, which affect performance, security, and code… Code Crack...