I have an XML in the following format
<Attachment>
<AttachmentName>Top Nav Menu.docx</AttachmentName>
<Subject>Attachment1</Subject>
<Sender>JameelM#orioninc.com</Sender>
</Attachment>
I want to attach another Attachment like above after the attachment close node. Below are the code that i have written for writing xml file
var doc = new XDocument(
new XDeclaration("1.0", "utf-16", "true"),
new XProcessingInstruction("test", "value"),
new XElement("Attachment",new XElement("AttachmentName", attachment.Name),
new XElement("Subject", exchangeEmailInformation.Subject),
new XElement("Sender", exchangeEmailInformation.Sender
)));
doc.Save(ConfigInformation.BackUpPath + FolderId[index]+"\\Attachments"+index+".xml");
Create root node for your attachments:
var doc = new XDocument(
new XDeclaration("1.0", "utf-16", "true"),
new XProcessingInstruction("test", "value"),
new XElement("Attachments",
new XElement("Attachment",
new XElement("AttachmentName", attachment.Name),
new XElement("Subject", exchangeEmailInformation.Subject),
new XElement("Sender", exchangeEmailInformation.Sender)
)));
When you decide to append another attachment, load document and add attachment to root:
doc.Root.Add(new XElement("Attachment",
new XElement("AttachmentName", attachment.Name),
new XElement("Subject", exchangeEmailInformation.Subject),
new XElement("Sender", exchangeEmailInformation.Sender)
));
I would use the XMLSerializer class. There you can handle your XML files just as if they are classes. Just have a look, you will like it :)
Load XML -> Use Classes in Code (modify, delete, add) -> Serialize back into XML
Related
I'm creating a Windows Phone 8.1 app, and I need to serialize my data to XML.
I have two functions; the first one is creating a document where I can later put my retrieved data.
public async Task make()
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root")
);
xml.Save(questions);
}
}
The second one is making serialization to my xml file:
public async Task serial(Tsk tak)
{
using (var questions = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
"data.xml",
CreationCollisionOption.OpenIfExists))
{
XDocument xml = XDocument.Load(questions);
xml.Root.Add(new XAttribute("Date", tak.Date),
new XElement("time", tak.Time),
new XElement("text", tak.Text)
);
xml.Save(questions);
}
}
The first xml function is making this code:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root />
When I'm running the second function I've got this error: root element is missing. Can anyone tell me how I can get this serialization to work?
Try this, you might need to doctor it a bit:
1) create the document
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
doc.AppendChild(root);
file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml");
await FileIO.WriteTextAsync(file, doc.GetXml());
Debug.WriteLine("Done creating file.");
2) write the new data to the document
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
XDocument doc = XDocument.Load(file.Path);
XElement newQuestion = new XElement("Question",
new XElement("time", tak.Time),
new XElement("text", tak.Text)
).SetAttributeValue("Date", tak.Date);
doc.Root.Add(newQuestion);
await FileIO.WriteTextAsync(file, doc.Root.ToString());
I have the following XML string in database.
<?xml version="1.0" encoding="utf-16"?>
<ServiceList>
<Service>
<COMPAT>2</COMPAT>
<EQUIPID>0</EQUIPID>
<TITLE>Collect Call and SMS</TITLE>
<SMSCOMMAND>0</SMSCOMMAND>
<DIALCOMMAND>123</DIALCOMMAND>
<DEACTIVATIONCOMMAND>0</DEACTIVATIONCOMMAND>
<MODE>Dial</MODE>
<DETAIL>Here you go.</DETAIL>
<IMAGE>2014-16-9--16-28-25</IMAGE>
<LONGDESC>
<![CDATA[<p>P<br />P<br />P </p>]]>
</LONGDESC>
<Mechanism>
<Title>Mech Title</Title>
<Description>Here you go.</Description>
<Trigger>Mech Trigger</Trigger>
<Controls>1</Controls>
</Mechanism>
</Service>
</ServiceList>
I need to add/appened the following element inside ServiceList
<Service>
<COMPAT>2</COMPAT>
<EQUIPID>0</EQUIPID>
<TITLE>Collect Call and SMS</TITLE>
<SMSCOMMAND>0</SMSCOMMAND>
<DIALCOMMAND>123</DIALCOMMAND>
<DEACTIVATIONCOMMAND>0</DEACTIVATIONCOMMAND>
<MODE>Dial</MODE>
<DETAIL>Here you go.</DETAIL>
<IMAGE>2014-16-9--16-28-25</IMAGE>
<LONGDESC><![CDATA[<p>P<br />P<br />P </p>]]></LONGDESC>
<Mechanism>
<Title>Mech Title</Title>
<Description>Here you go.</Description>
<Trigger>Mech Trigger</Trigger>
<Controls>1</Controls>
</Mechanism>
</Service>
The c# code is given below where i am creating the document
XElement ServiceList =
new XElement("ServiceList",
new XElement("Service",
new XElement("COMPAT", "2"),
new XElement("EQUIPID", equipId),
new XElement("TITLE", form["Title"]),
new XElement("SMSCOMMAND", smscommand),
new XElement("DIALCOMMAND",dialcommand),
new XElement("DEACTIVATIONCOMMAND", smsdecactivationcommand),
new XElement("MODE", mode),
new XElement("DETAIL", form["Detail"]),
new XElement("IMAGE", Datetime),
new XElement("LONGDESC", new XCData(htmlstring)),
new XElement("Mechanism",
new XElement("Title", form["Mechanism.Title"]),
new XElement("Description", form["Mechanism.Description"]),
new XElement("Trigger", form["Mechanism.Triger"]),
new XElement("Controls", form["Mechanism.Controls"])
)
));
XDocument xml = new XDocument(ServiceList);
I simply convert the above document to string with the help of the following method and insert it to database as string.
public string GetXMLAsString(XDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();
return str;
}
Assuming that you're able to get the XML string back from database and store it in a string variable xml, then you can load it to XDocument as follow :
string xml;
.....
XDocument doc = XDocument.Parse(xml);
And assuming that you can construct the new <Service> node as an XElement object referenced by variable newService, you can easily append it to the doc using XElement.Add() method :
XElement newService;
.....
doc.Root.Add(newService);
Then you need to replace the XML in your database with updated XML :
string updatedXml = doc.ToString();
//save updatedXml to your database
You can easily get XML content by calling ToString() on the XDocument object, as shown in above example.
I made a webpage using c# asp.net. It has various text fields and dropdown lists and a radio button. Now i want to save the data into an xml file. and i'm not really able to understand on how to go about it.
The various attributes in my page are TEXTBOX: GInfo; LNo; Org; UName; SType; Ver; MeapSupp; MaxUser; MaxMach; MachIP; MachMac; UqID
DROPDOWNLIST: LType
RADIO BUTTON: MeapSupp
I'm new to XML and asp.net and c#. Can you please help me out.
You can use this code - based on XmlTextWriter class
XmlTextWriter textWriter = new XmlTextWriter("yourpath", null);
// Opens the document
textWriter.WriteStartDocument();
textWriter.WriteStartElement("root");
textWriter.WriteAttributeString("xmlns", "x", null, "urn:1");
// Write comments
textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
textWriter.WriteEndElement();
// Ends the document.
textWriter.WriteEndDocument();
// close writer
textWriter.Close();
Link : http://msdn.microsoft.com/fr-fr/library/system.xml.xmltextwriter.aspx
You can also use LINQ To XML
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("This is a test"),
new XElement("root")
);
var root = doc.CreateElement("Test");
....
Link : http://msdn.microsoft.com/en-us/library/bb387098.aspx
i am validating a Xml file with an existing Xsd schema. Is it possible to update the Xml with the xsd file if the validation fails?
After Error you can execute this code
var schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema1.xsd");
// add further schemas as needed
schemaSet.Compile();
var xmlSampleGenerator= new XmlSampleGenerator(schemaSet, new XmlQualifiedName("Test"));
var doc = new XmlDocument();
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
xmlSampleGenerator.WriteXml(writer);
}
Link : http://msdn.microsoft.com/en-us/library/aa302296.aspx
I want to create an XML document like this:
I want to create it from scratch using code and LINQ-to-XML. In the form Load Event I've written this code:
private void Form9_Load(object sender, EventArgs e)
{
doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement myroot = new XElement("Employees");
doc.Add(myroot);
}
How I can add new person to Employees, and if I want to insert person in specific location what can I do?
How I can delete or update a specific person ?
Search element you want to add and use Add method as shown below
xDoc.Element("content")
.Elements("item")
.Where(item => item.Attribute("id").Value == "2").FirstOrDefault()
.AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));
or
<Microsoft>
<DOTNet>
</DOTNet>
</Microsoft>
private void addToXml()
{
XDocument xmlDoc = XDocument.Load("yourfile.xml");
xmlDoc.Element("Microsoft").Add(new XElement("DOTNet", new XElement("Name", "Nisar"),
new XElement("Forum", "dotnetobject"), new XElement("Position", "Member")));
xmlDoc.Save("yourfile.xml");
readXml();
}
<Microsoft>
<DOTNet>
<Name>Nisar</Name>
<Forum>dotnetobject</Forum>
<Position>Member</Position>
</DOTNet>
</Microsoft>