我正在尝试通过在字段/属性([XmlAttribute]
,[XmlElement]
等上应用属性来创建XML文档。)我的问题是我要求附加一个附加属性到以下样式的原始数据类型:
<document xmlns:dt="urn:schemas-microsoft-com:datatypes" >
<binary addAttribute="X" dt:dt="bin.base64">
[... binary ...]
</binary>
</document>
我正在使用如下代码:
[Serializable]
public class Document {
[XmlElement]
public BinaryObject Binary { get; set; }
}
[Serializable]
public class BinaryObject {
[XmlText(DataType = "base64Binary")]
public byte[] Binary { get; set; }
[XmlAttribute]
public int AddAttribute { get; set; }
}
public class XmlExample {
public static void Main(string[] args)
{
Document document = new Document();
document.Binary = new BinaryObject();
document.Binary.Binary = File.ReadAllBytes(@"FileName");
document.Binary.AddAttribute = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Document));
serializer.Serialize(Console.Out, document);
Console.ReadLine();
}
}
但是,这提供了以下输出:
<document>
<binary addAttribute="X">
[... binary ...]
</binary>
</document>
如果我尝试将byte[] Binary
移至Document
课程,我可以按预期获得xmlns:dt="..."
,但是当我这样做时,我无法附加任意addAttribute
除非我错过了一些明显的东西。)这是不正确的;我误读了我从XML中获取的XML。在这种情况下,未添加xmlns:dt
元素。
问题是:我可以通过C#属性完全执行此操作(同时具有DataType和addAttribute)吗?
答案 0 :(得分:1)
这个问题的答案部分来自:XmlSerializer attribute namespace for element type dt:dt namespace。 DataType =&#34; base64Binary&#34; 不将xmlns:dt="urn:schemas-microsoft-com:datatypes" dt:dt="bin.base64"
应用于附加到的元素。必须将属性添加到BinaryObject
,以便为dt:dt = "bin.base64"
提供正确的名称空间。
最终代码
[Serializable]
public class Document {
public BinaryObject Binary { get; set; }
}
[Serializable]
public class BinaryObject {
[XmlText]
public byte[] Binary { get; set; }
[XmlAttribute]
public int AddAttribute { get; set; }
// Adds the dt:dt object to the correct name space.
[XmlAttribute("dt", Namespace = "urn:schemas-microsoft-com:datatypes")]
public string DataType { get; set; }
public BinaryObject() { DataType = "bin.base64"; }
}
public class XmlExample {
public static void Main(string[] args)
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
// Adds the needed namespace to the document.
namespaces.Add("dt", "urn:schemas-microsoft-com:datatypes");
Document document = new Document();
document.Binary = new BinaryObject();
document.Binary.Binary = new byte[]{0,1,2,3,4,5,6,7,8,9};
document.Binary.AddAttribute = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Document));
serializer.Serialize(Console.Out, document, namespaces);
Console.ReadLine();
}
}
最终输出
<Document xmlns:dt="urn:schemas-microsoft-com:datatypes">
<Binary AddAttribute="0" dt:dt="bin.base64">AAECAwQFBgcICQ==</Binary>
</Document>
答案 1 :(得分:0)
试试这个
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
[XmlRoot("Document")]
public class Document
{
[XmlText(DataType = "base64Binary")]
public byte[] Binary { get; set; }
[XmlAttribute]
public int AddAttribute { get; set; }
}
}