当我尝试序列化类型时,我一直在使用的应用程序失败.
像这样的陈述
XmlSerializer lizer = new XmlSerializer(typeof(MyType));
Run Code Online (Sandbox Code Playgroud)
生产:
System.IO.FileNotFoundException occurred
Message="Could not load file or assembly '[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified."
Source="mscorlib"
FileName="[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
FusionLog=""
StackTrace:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
Run Code Online (Sandbox Code Playgroud)
我没有为我的班级定义任何特殊的序列化器.
我该如何解决这个问题?
我有以下方法将对象保存到文件:
// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
TextWriter textWriter = new StreamWriter(filename);
xmlSerializer.Serialize(textWriter, toSerialize);
textWriter.Close();
}
Run Code Online (Sandbox Code Playgroud)
我承认我没有写它(我只将其转换为带有类型参数的扩展方法).
现在我需要它将xml作为字符串返回给我(而不是将其保存到文件中).我正在研究它,但我还没想到它.
我认为对于熟悉这些对象的人来说这可能很容易.如果不是,我最终会弄明白.
我有一个我继承的C#类.我已成功"建立"了这个对象.但我需要将对象序列化为XML.有一个简单的方法吗?
看起来这个类已经设置为序列化,但我不知道如何获得XML表示.我的类定义如下所示:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
...
}
Run Code Online (Sandbox Code Playgroud)
这是我认为我可以做的,但它不起作用:
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
Run Code Online (Sandbox Code Playgroud)
如何获取此对象的XML表示?
所以我通过OAuth从Twitter中提取XML
所以我正在向http://twitter.com/account/verify_credentials.xml提出请求
返回以下XML
<?xml version="1.0" encoding="UTF-8"?>
<user>
<id>16434938</id>
<name>Lloyd Sparkes</name>
<screen_name>lloydsparkes</screen_name>
<location>Hockley, Essex, UK</location>
<description>Student</description>
<profile_image_url>http://a3.twimg.com/profile_images/351849613/twitterProfilePhoto_normal.jpg</profile_image_url>
<url>http://www.lloydsparkes.co.uk</url>
<protected>false</protected>
<followers_count>115</followers_count>
<profile_background_color>9fdaf4</profile_background_color>
<profile_text_color>000000</profile_text_color>
<profile_link_color>220f7b</profile_link_color>
<profile_sidebar_fill_color>FFF7CC</profile_sidebar_fill_color>
<profile_sidebar_border_color>F2E195</profile_sidebar_border_color>
<friends_count>87</friends_count>
<created_at>Wed Sep 24 14:26:09 +0000 2008</created_at>
<favourites_count>0</favourites_count>
<utc_offset>0</utc_offset>
<time_zone>London</time_zone>
<profile_background_image_url>http://s.twimg.com/a/1255366924/images/themes/theme12/bg.gif</profile_background_image_url>
<profile_background_tile>false</profile_background_tile>
<statuses_count>1965</statuses_count>
<notifications>false</notifications>
<geo_enabled>false</geo_enabled>
<verified>false</verified>
<following>false</following>
<status>
<created_at>Mon Oct 12 19:23:47 +0000 2009</created_at>
<id>4815268670</id>
<text>» @alexmuller your kidding? it should all be "black tie" dress code</text>
<source><a href="http://code.google.com/p/wittytwitter/" rel="nofollow">Witty</a></source>
<truncated>false</truncated>
<in_reply_to_status_id>4815131457</in_reply_to_status_id>
<in_reply_to_user_id>8645442</in_reply_to_user_id>
<favorited>false</favorited>
<in_reply_to_screen_name>alexmuller</in_reply_to_screen_name>
<geo/>
</status>
</user>
Run Code Online (Sandbox Code Playgroud)
我使用以下代码来反序列化
public User VerifyCredentials()
{
string …
Run Code Online (Sandbox Code Playgroud) 我正在编写代码来进行Xml序列化.具有以下功能.
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
如果参数是没有无参数构造函数的类的实例,它将抛出异常.
未处理的异常:System.InvalidOperationException:CSharpConsole.Foo无法序列化,因为它没有无参数构造函数.System.Xml.Serialization.ModelScope.GetTypeModel的System.Xml.Serialization.TypeScope.GetTypeDesc(Type type,MemberInfo sourc e,Boolean directReference,Boolean throwOnError)中的System.Xml.Serialization.TypeDesc.CheckSupported()处于类型类型, System.Xml.Serialization上的System.Xml.Serialization.XmlSerializer..ctor(Type type,String defaultName space)中System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type,XmlRootAttribute root,String defaultNamespace)的布尔直接引用. XmlSerializer..ctor(类型类型)
为什么必须有一个无参数构造函数才能使xml序列化成功?
编辑:感谢cfeduke的回答.无参数构造函数可以是私有的或内部的.
我通过套接字接收XML字符串,并希望将它们转换为C#对象.
消息的形式如下:
<msg>
<id>1</id>
<action>stop</action>
</msg>
Run Code Online (Sandbox Code Playgroud)
我是.Net的新手,并不确定执行此操作的最佳做法.我之前使用过JAXB for Java,并且不确定是否有类似的东西,或者是否会以不同的方式处理.
一旦程序员决定实施IXmlSerializable
,实施它的规则和最佳实践是什么?我听说GetSchema()
应该返回null
并且ReadXml
应该在返回之前移动到下一个元素.这是真的?那么WriteXml
- 它应该为对象写一个根元素还是假设根已经写好了?儿童对象应如何处理和书写?
这是我现在拥有的样本.当我得到好的回复时,我会更新它.
public class MyCalendar : IXmlSerializable
{
private string _name;
private bool _enabled;
private Color _color;
private List<MyEvent> _events = new List<MyEvent>();
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyCalendar")
{
_name = reader["Name"];
_enabled = Boolean.Parse(reader["Enabled"]);
_color = Color.FromArgb(Int32.Parse(reader["Color"]));
if (reader.ReadToDescendant("MyEvent"))
{
while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyEvent")
{
MyEvent evt = new …
Run Code Online (Sandbox Code Playgroud) 给出以下XML:
<?xml version="1.0"?>
<user_list>
<user>
<id>1</id>
<name>Joe</name>
</user>
<user>
<id>2</id>
<name>John</name>
</user>
</user_list>
Run Code Online (Sandbox Code Playgroud)
以下课程:
public class User {
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用XmlSerializer
将xml反序列化为List<User>
?如果是这样,我需要使用哪种类型的附加属性,或者我需要使用哪些其他参数来构造XmlSerializer
实例?
User[]
如果有点不太可取的话,array()是可以接受的.
代码如下所示:
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using (XmlWriter xmlWriter = XmlWriter.Create(builder, settings))
{
XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
s.Serialize(xmlWriter, objectToSerialize);
}
Run Code Online (Sandbox Code Playgroud)
生成的序列化文档包含名称空间,如下所示:
<message xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns="urn:something">
...
</message>
Run Code Online (Sandbox Code Playgroud)
要删除xsi和xsd命名空间,我可以按照如何将对象序列化为XML而不获取xmlns ="..."的答案?.
我希望我的消息标记为<message>
(没有任何命名空间属性).我怎样才能做到这一点?
有没有办法配置XmlSerializer,以便它不会在根元素中写入默认命名空间?
我得到的是这个:
<?xml ...>
<rootelement xmlns:xsi="..." xmlns:xsd="...">
</rootelement>
Run Code Online (Sandbox Code Playgroud)
我想删除两个xmlns声明.