`I am doing in C#. I have certain elements and attributes. In addition to this certain attributes I need to create dynamically at run time. These attributes are kept in a text file. At run time these attributes have to be picked up and based on all these attributes xml should be generated. Currently I am getting xml as :
<btm>
<test testin="abc" isform="true" address="0" compressionType="9">
<advancedSettings>
<AdvancedSettings name=" TimeIntervalMin"/>
<AdvancedSettings name=" GroupID"/>
<AdvancedSettings name=" Blabla2"/>
</advancedSettings>
</test>
</btm>
Ideally I want
<btm>
<test testin="abc" address="0" Type="9" TimeIntervalMin="" GroupID="" Blabla2="" >
</test>
</btm>`
Those shown in advanaced settings are got from text file. How to do this.
My code:
public class AdvancedSettings
{
[XmlAttribute]
public string name { get; set; }
public string value { get; set; }
}
[XmlRoot]
public class btm
{
[XmlElement("test")]
public List<info>information;
}
public class info : ISerializable
{
public info() { }
[XmlAttribute]
public string ID { get; set; }
[XmlAttribute]
public int Address { get; set; }
[XmlAttribute]
public int comType { get; set; }
public List<AdvancedSettings> advancedSettings = new List<AdvancedSettings>();
}
This is wrong I know. BUt I dont know how to correct it.Please help.
<btm>
<test testin="abc" Address="0" compressionType="9">
<advancedSettings>
<AdvancedSettings name=" TimeIntervalMin"/>
<AdvancedSettings name=" GroupID"/>
<AdvancedSettings name=" Blabla2"/>
</advancedSettings>
</test>
</btm>
Thhis is what I got which is wrong. I want the text file elements as attributes not elements`
You can compose XML dynamically on the fly via LINQ to XML.
It is available in the .Net Framework since 2007.
c#
void Main()
{
// static part
XElement xelem = new XElement("BottomAssembly",
new XElement("Tool",
new XAttribute("toolID", "abc"),
new XAttribute("IsMWDTool", "true"),
new XAttribute("slaveAddress", "0"),
new XAttribute("compressionType", "9")
)
);
Console.WriteLine(xelem);
// add XML attributes dynamically as you wish, loop through *.txt file, etc.
xelem.Element("Tool").Add(new XAttribute("TimeIntervalMin", "206"));
xelem.Element("Tool").Add(new XAttribute("GroupID", "18"));
Console.WriteLine(xelem);
}
Output
<BottomAssembly>
<Tool toolID="abc" IsMWDTool="true" slaveAddress="0" compressionType="9" />
</BottomAssembly>
<BottomAssembly>
<Tool toolID="abc" IsMWDTool="true" slaveAddress="0" compressionType="9" TimeIntervalMin="206" GroupID="18" />
</BottomAssembly>