gpt4 book ai didi

c# - 在 C# 中更改由 XmlSerializer 生成的 XML 结构

转载 作者:数据小太阳 更新时间:2023-10-29 02:15:40 25 4
gpt4 key购买 nike

我有如下类(class)

namespace Coverage {
public class ClassInfo {
public string ClassName;
public int BlocksCovered;
public int BlocksNotCovered;

public ClassInfo() {}

public ClassInfo(string ClassName, int BlocksCovered, int BlocksNotCovered)
{
this.ClassName = ClassName;
this.BlocksCovered = BlocksCovered;
this.BlocksNotCovered = BlocksNotCovered;
}
}

public class Module {
public List<ClassInfo> ClassInfoList;
public int BlocksCovered;
public int BlocksNotCovered;
public string moduleName;

public Module()
{
ClassInfoList = new List<ClassInfo>();
BlocksCovered = 0;
BlocksNotCovered = 0;
moduleName = "";
}

使用以下序列化程序代码

XmlSerializer SerializerObj = new XmlSerializer(typeof(Module));
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@"test.xml");
SerializerObj.Serialize(WriteFileStream, report);
WriteFileStream.Close();

我可以获得以下 XML 文件。

<?xml version="1.0" encoding="utf-8"?>
<Module xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ClassInfoList>
<ClassInfo>
<ClassName>Fpga::TestMe</ClassName>
<BlocksCovered>4</BlocksCovered>
<BlocksNotCovered>8</BlocksNotCovered>
</ClassInfo>
<ClassInfo>
<ClassName>Fpga::TestMe2</ClassName>
<BlocksCovered>4</BlocksCovered>
<BlocksNotCovered>8</BlocksNotCovered>
</ClassInfo>
</ClassInfoList>
<BlocksCovered>8</BlocksCovered>
<BlocksNotCovered>16</BlocksNotCovered>
<moduleName>helloclass.exe</moduleName>
</Module>
  • 问题 1:如何删除 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://...拥有简单的元素<Module>..</Module>
  • Q2 : XML 元素名称与类名或变量名完全相同。我可以用自己的代替吗?
  • Q3:我可以去掉外面的<ClassInfoList>吗? ?

例如,我如何生成如下 XML:

<?xml version="1.0" encoding="utf-8"?>
<Module>
<Class>
<ClassName>Fpga::TestMe</ClassName>
<BlocksCovered>4</BlocksCovered>
<BlocksNotCovered>8</BlocksNotCovered>
</Class>
<Class>
<ClassName>Fpga::TestMe2</ClassName>
<BlocksCovered>4</BlocksCovered>
<BlocksNotCovered>8</BlocksNotCovered>
</Class>
<BlocksCovered>8</BlocksCovered>
<BlocksNotCovered>16</BlocksNotCovered>
<moduleName>helloclass.exe</moduleName>
</Module>

最佳答案

(顺便说一句,它与问题无关,但由于许多 stackoverflow 问题中涵盖的许多原因,您应该尽量避免使用公共(public)字段)

Q3:简单地说:

[XmlElement("Class")]
public List<ClassInfo> ClassInfoList;

Q2 是顶级名称;你可以使用

[XmlRoot("somethingFun")]
public class Module { ... }

Q2成员姓名:

[XmlElement("blocks")]
public int BlocksCovered;

(另见 [XmlAttribute(...)])

Q1 可以使用 XmlSerializerNamespaces 删除 xsi 等:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var ser = new XmlSerializer(typeof(Module));
ser.Serialize(destination, module, ns);

关于c# - 在 C# 中更改由 XmlSerializer 生成的 XML 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com