`我正在用 C# 做。我有某些元素和属性。除了这些某些属性之外,我还需要在运行时动态创建。这些属性保存在文本文件中。在运行时,必须获取这些属性,并根据所有这些属性生成 xml。目前我得到的 xml 为:
<BottomAssembly>
<Tool toolID="abc" IsMWDTool="true" slaveAddress="0" compressionType="9">
<advancedSettings>
<AdvancedSettings name=" TimeIntervalMin"/>
<AdvancedSettings name=" GroupID"/>
<AdvancedSettings name=" Blabla2"/>
</advancedSettings>
</Tool>
</BottomAssembly>
我想要的理想情况
<BottomHoleAssembly>
<Tool toolID="abc" IsMWDTool="true" slaveAddress="0" compressionType="9" TimeIntervalMin="" GroupID="" Blabla2="" >
</Tool>
</BottomHoleAssembly>`
高级设置中显示的内容是从文本文件中获取的。如何做到这一点。
我的代码:
public class AdvancedSettings
{
[XmlAttribute]
public string name { get; set; }
public string value { get; set; }
}
[XmlRoot]
public class BottomAssembly
{
[XmlElement("Tool")]
public List<lwdinformation> toolInformation;
}
public class lwdinformation : ISerializable
{
public lwdinformation() { }
[XmlAttribute]
public string toolID { get; set; }
[XmlAttribute]
public bool IsMWDTool { get; set; }
[XmlAttribute]
public int slaveAddress { get; set; }
[XmlAttribute]
public int compressionType { get; set; }
public List<AdvancedSettings> advancedSettings = new List<AdvancedSettings>();
}
我知道这是错误的。但我不知道如何纠正它。请帮忙。
<BottomAssembly>
<Tool toolID="abc" IsMWDTool="true" slaveAddress="0" compressionType="9">
<advancedSettings>
<AdvancedSettings name=" TimeIntervalMin"/>
<AdvancedSettings name=" GroupID"/>
<AdvancedSettings name=" Blabla2"/>
</advancedSettings>
</Tool>
</BottomAssembly>
这是我得到的,这是错误的。我希望文本文件元素作为属性而不是元素`
使用以下:
[XmlRoot("BottomHoleAssembly")]
public class BottomAssembly
{
[XmlElement("Tool")]
public lwdinformation toolInformation;
}
public class lwdinformation
{
[XmlAttribute]
public string toolID { get; set; }
[XmlAttribute]
public bool IsMWDTool { get; set; }
[XmlAttribute]
public int slaveAddress { get; set; }
[XmlAttribute]
public int compressionType { get; set; }
[XmlAttribute]
public TimeIntervalMin { get ;set; }
[XmlAttribute]
public GroupID { get ;set; }
[XmlAttribute]
public Blabla2 { get ;set; }
}
您可以通过 LINQ to XML 动态地编写 XML。
自 2007 年以来,它在 .Net Framework 中可用。
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);
}
输出
<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>