[英]XmlSerializer to have attribute and prefix in XML file
我可以使用 XmlSerializer 從 C# 類中獲取這個 XML 文件。
<?xml version="1.0" encoding="utf-8"?>
<Component xmlns:spirit="b" xmlns:chrec="a" MovieName="0" BlocksNotCovered="0">
<ClassInfoList>
<chrec:string>hello</chrec:string>
<chrec:string>world</chrec:string>
</ClassInfoList>
<moduleName />
<world>
<x>10</x>
<y>20</y>
</world>
</Component>
如何為 chrec 和 spriti 添加前綴命名空間? 例如,我怎樣才能得到這個 XML 文件?
<?xml version="1.0" encoding="utf-8"?>
<spirit:Component xmlns:spirit="b" xmlns:chrec="a" MovieName="0" BlocksNotCovered="0">
<spirit:ClassInfoList>
<chrec:string>hello</chrec:string>
<chrec:string>world</chrec:string>
</spirit:ClassInfoList>
<spirit:moduleName />
<chrec:world>
<chrec:x>10</chrec:x>
<chrec:y>20</chrec:y>
</chrec:world>
</spirit:Component>
這是 C# 代碼。
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Linq;
namespace Coverage
{
public class Hello
{
public int x;
public int y;
public Hello()
{
x = 10;
y = 20;
}
}
public class Component {
[XmlAttribute("MovieName")]
public int MovieName;
[XmlAttribute("BlocksNotCovered")]
public int BlocksNotCovered;
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces ns;
public List<string> ClassInfoList;
public string moduleName;
public Hello world;
public Component()
{
ClassInfoList = new List<string>() {"hello", "world"};
MovieName = 0;
BlocksNotCovered = 0;
moduleName = "";
world = new Hello();
}
}
class Cov2xml
{
static void Main(string[] args)
{
string xmlFileName = "perf.xml";
Component report = new Component();
TextWriter writeFileStream = new StreamWriter(xmlFileName);
report.ns = new XmlSerializerNamespaces();
report.ns.Add("chrec","a");
report.ns.Add("spirit","b");
var ser = new XmlSerializer(typeof(Component));
ser.Serialize(writeFileStream, report, report.ns);
writeFileStream.Close();
}
}
}
感謝來自competent_tech的鏈接,我可以找到方法。
您可以使用 XmlRootAttribute,重要的是名稱空間是名稱空間,而不是名稱空間名稱。 在示例中,它應該是“b”而不是“chrec”。
[XmlRootAttribute("Component", Namespace="http://namespace", IsNullable = false)]
public class Component {
您可以在變量之前使用 XmlElement。
[XmlElement("xyz", Namespace="http://www.namespace", IsNullable = false)]
int x;
你會得到這個。
<?xml version="1.0" encoding="utf-8"?>
<chrec:Component xmlns:spirit="http:..." MovieName="0" BlocksNotCovered="0" xmlns:chrec="...">
<chrec:ClassInfoList>
<chrec:string>hello</chrec:string>
<chrec:string>world</chrec:string>
</chrec:ClassInfoList>
<chrec:moduleName />
<chrec:world>
<spirit:xyz>10</spirit:xyz>
<chrec:y>20</chrec:y>
</chrec:world>
</chrec:Component>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.