Reputation:
I can't write the value of a string variable using XElement
to an .xml file.
I tried use System.IO
:
XDocument
, XElement
code.cs:
string variable ="sth";
XDocument xml_cip_c1 = new XDocument(
new XComment("document"),
new XElement("new root"),
new XElement("name", variable)
);
result.xml:
<!--document-->
<new root>
<name />
</new root>
Upvotes: 0
Views: 603
Reputation:
I use method from first post,
code .cs:
private void sb_button_click(object sender, RoutedEventArgs e)
{
variable1 = przycisk.Text;
name_of_file_xml.Save(path_of_file);
}
static string variable1 ="sth";
I must use static var because it requires XAttribute from me.
I must use string with value, because if I declare string outwith value:
static string zmienna1 = null;
System.ArgumentNullException: 'The value cannot be zero.
code .cs:
Parameter name: value '
XDocument name_of_file_xml = new XDocument(
new XComment("document"),
new XElement("root",
new XElement("name", new XAttribute ("name2", variable1 ))
)
);
In my project I would like to have a variable without value, is it possible?
because It don't assign the variable from button.text to me but the one set at the beginning
Upvotes: -1
Reputation: 1453
Here you are Sir. Use Value
property:
var yourVariable = "ABC";
XDocument xml_cip_c1 = new XDocument(
new XComment("document"),
new XElement("new_root",
new XElement("name") { Value = yourVariable}));
This will produce the following output:
<?xml version="1.0" encoding="utf-8"?>
<!--document-->
<new_root>
<name>ABC</name>
</new_root>
But if you would like to add Attribute to your xml element, use the following code that uses XAttribute
:
XDocument xml_cip_c1 = new XDocument(
new XComment("document"),
new XElement("new_root",
new XElement("name", new XAttribute("name", yourVariable))));
Then you will get the following xml file:
<?xml version="1.0" encoding="utf-8"?>
<!--document-->
<new_root>
<name name="ASD" />
</new_root>
Upvotes: 3
Reputation: 36
try this,
.cs Code
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent =true;
settings.IndentChars = (" ");
settings.CloseOutput = true;
settings.OmitXmlDeclaration =true;
using (XmlWriter writer = XmlWriter.Create("FileName.xml", settings))
{
writer.WriteStartElement("newroot");
writer.WriteElementString("name", "ABC");
writer.WriteEndElement();
writer.Flush();
}
Result => XML File
<?xml version="1.0" encoding="utf-8" ?>
<newroot>
<name>ABC</name>
</newroot>
Upvotes: 1