我正在尝试反序列化以下XML输出:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Foo>
<Val>Data1</Val>
</Foo>
<Foo>
<Val>Data2</Val>
</Foo>
Run Code Online (Sandbox Code Playgroud)
(这是从硬件设备输出,不能更改)
我有一个XML类型定义为:
[XmlType(AnonymousType=true, Namespace="")]
public class Foo
{
public string Val { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我试图通过创建一个序列化器来反序列化这个数组:
var s = new XmlSerializer(typeof(Foo[]));
//or
var s = new XmlSerializer(typeof(List<Foo>);
Run Code Online (Sandbox Code Playgroud)
但每次调用s.Deserialize()都会导致InvalidOperaitonException:
System.InvalidOperationException: <Foo xmlns=''> was not expected.
Run Code Online (Sandbox Code Playgroud)
注意
var s = new XmlSerializer(typeof(Foo));
// Only deseralizes the first Foo (Data1).
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
我正在生成一个xml文件.我在文件中注意到它有一个我不想要的标签.我正在从xmlSerializer对象生成xml文件,它正在做什么是在我的对象上处理一个属性错误...我的对象上的proerty像这样lloks ...
public List<ProductVarient> Varients { get; set; }
Run Code Online (Sandbox Code Playgroud)
因此,当我序列化它时,我得到一个这样的结构
<Varients>
<ProductVarient>
<Name>Nick</Name>
......
Run Code Online (Sandbox Code Playgroud)
我想要的
<AnotherProp>
<Stuff>toys</Stuff>
</AnotherProp>
<ProductVarient>
<Name>Nick</Name>
</ProductVarient>
<ProductVarient>
<Name>Jeff</Name>
</ProductVarient>
....
Run Code Online (Sandbox Code Playgroud)
因此,我没有尝试解决xmlserializer,而是使用超级黑客并编写了此代码
string s = File.ReadAllText(path);
s.Replace("<Varients>", "");
s.Replace("</Varients>", "");
using (FileStream stream = new FileStream(path, FileMode.Create))
using (TextWriter writer = new StreamWriter(stream))
{
writer.WriteLine("");
writer.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)
2个问题
- 我写的代码不会替换为"",它不会抛出异常,但它也不起作用,我不知道为什么? - 有一个快速更好的方法来完成我的问题.
我仍然试图围绕整个xml序列化事物包围我的脑子,看起来我又需要一些帮助了.
我需要能够反序列化抽象类型的属性.这种类型将随着时间的推移而添加许多不同的具体类型,并且在许多不同的模型中被引用,因此明确列出每种具体类型并不是理想的解决方案.
我已经阅读了XML Serialization和Inherited Types线程,并提出了以下内容:
<Page>
<introCommand>
<PlayElement />
</introCommand>
</Page>
Run Code Online (Sandbox Code Playgroud)
**
namespace TestService
{
public class Page
{
[XmlElement("introCommand", Type = typeof(XmlCommandSerializer<AbstractCommandModel>))]
//[XmlElement(typeof(PlayElement))] **NOTE: the example works if I use this instead
public AbstractCommandModel introCommand;
}
}
Run Code Online (Sandbox Code Playgroud)
**
namespace TestService
{
public class AbstractCommandModel
{
}
}
Run Code Online (Sandbox Code Playgroud)
**
namespace TestService
{
public class PlayElement : AbstractCommandModel
{
}
}
Run Code Online (Sandbox Code Playgroud)
**
namespace TestService
{
public class XmlCommandSerializer<AbstractCommandModel> : IXmlSerializable
{
// Override the Implicit Conversions Since the XmlSerializer …Run Code Online (Sandbox Code Playgroud) 假设我有一个具有名字,姓氏和年龄的Person对象.我想将此person对象发送到一个Web服务,该Web服务只知道并关心具有名字和姓氏的person对象.但我希望xml代表完整的人物对象,包括要发回的年龄.
我已经有了一种机制,可以将xml存储在幕后的对象中,并且可以简单地将xml提供给WCF,但我不想使用普通的XmlSerializer.我希望能够说"这里是xml.用肥皂包裹并发送".
我打算使用WCF.我将在哪里挂钩来控制序列化?
虽然这个问题的例子是人为的.它清楚地说明了我的问题.假设我有一个像这样的类的应用程序:
/* person A */
class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我将此传递给Web服务.Web服务知道编写的另一个Person类:
/* person B */
class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该服务具有以下方法签名的方法:
Person SomeOperation(Person p);
Run Code Online (Sandbox Code Playgroud)
当我从我的应用程序调用此Web服务并将其传递给我的人A版本时,Web服务就可以接收它了.它忽略了Age属性.但是当它重新创建响应时,Age属性会消失.
我明白为什么会这样.WCF将响应反序列化为实际的c#对象,因此丢弃随请求一起发送的额外XML.因此,没有Age属性可以发回.
我有一种机制来实际使用XML作为我的对象的后备存储.如果后备存储中存在该对象不需要的XML,则它只是位于那里并且未被使用.我希望在响应中发送用作后备存储的完整XML.
如果这是一个基本的c#应用程序,我可以简单地创建一个包含FirstName和LastName属性的IBasicPerson接口,并让Person类实现接口,如下面的代码:
public interface IBasicPerson {
string FirstName { get; set; }
string LastName { …Run Code Online (Sandbox Code Playgroud) 我需要将XML文件反序列化为对象.XML内容:
<Players dealerId="2">
<Player id="1">
<ScreenName>JetYeo</ScreenName>
</Player>
<Player id="2">
<ScreenName>Test</ScreenName>
</Player>
</Players>
Run Code Online (Sandbox Code Playgroud)
我定义了一个对象类:
[Serializable()]
[XmlRoot("Players")]
public class Players
{
[XmlAttribute("dealerId")]
public int DealerId { get; set; }
[XmlArrayItem("Player", typeof(Player))]
public Player[] Players { get; set; }
}
[Serializable()]
[XmlRoot("Player")]
public class Player
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("ScreenName")]
public string ScreenName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是,反序列化不起作用:Players数组为null.请帮我解决一下.谢谢.
我想生成遵循OWL格式的RDF代码.我能够生成一个RDF文件,但我需要将其转换为OWL.下面是我可以生成的RDF.
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:ns1="http://example.com/nodetypes/2012/04/24/vehicle/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
<rdf:Description rdf:about="http://example.com/nodetypes/2012/04/24/vehicle/2">
<ns1:nodetype_ptr_id>2</ns1:nodetype_ptr_id>
<ns1:slug>vehicle</ns1:slug>
<ns1:last_update>2012-04-24 23:49:36.633689</ns1:last_update>
<ns1:end_publication>2042-03-15 00:00:00</ns1:end_publication>
<ns1:tree_id>2</ns1:tree_id>
<ns1:featured>False</ns1:featured>
<ns1:parent_id>None</ns1:parent_id>
<ns1:content></ns1:content>
<ns1:rating_score>0</ns1:rating_score>
<ns1:rating_votes>0</ns1:rating_votes>
<ns1:start_publication>2012-04-24 23:49:15</ns1:start_publication>
<ns1:level>0</ns1:level>
<ns1:creation_date>2012-04-24 23:49:15</ns1:creation_date>
<ns1:status>2</ns1:status>
<ns1:template>gstudio/nodetype_detail.html</ns1:template>
<ns1:content_org>None</ns1:content_org>
<ns1:excerpt></ns1:excerpt>
<ns1:plural>vehicles</ns1:plural>
<ns1:comment_enabled>True</ns1:comment_enabled>
<ns1:password></ns1:password>
<ns1:title>vehicle</ns1:title>
<ns1:login_required>False</ns1:login_required>
<ns1:pingback_enabled>True</ns1:pingback_enabled>
<ns1:rurl></ns1:rurl>
</rdf:Description>
</rdf:RDF>
Run Code Online (Sandbox Code Playgroud) 我在一个Android应用程序上工作,我从JSON格式的服务器获得响应.我想将键值对存储在strings.xml中.怎么办呢?JSON响应如下.
{
"ResourceStrings": [
{
"Key": "AccountNumber",
"Value": "Account Number"
},
{
"Key": "AccountPassword",
"Value": "Account Password"
},
{
"Key": "AccountSettings",
"Value": "Account"
},
{
"Key": "AccountSettings.Load.InfoMessage",
"Value": "The Account Number and Password only needs to be set one time. \r\n\r\nIf you do not know the Account information please contact you system administrator or your DataXchange reseller."
},
{
"Key": "Add",
"Value": "Setup"
},
{
"Key": "AddandModifytheScreens",
"Value": "Add and Modify the Screens"
},
{
"Key": "AddButton",
"Value": "Add"
}, …Run Code Online (Sandbox Code Playgroud) 我正在对一个xml文件进行去序列化,我正在尝试使用下面的代码捕获所有异常艺术,但它只捕获一个异常.我在这做什么错?
码:
StringBuilder exBuilder;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var fileName = openFileDialog1.FileName;
mruOpenRseConfig.AddRecentFile(fileName);
try
{
ConfigDeserialized = MyConfig.DeserializeFromXmlFile(fileName);
}
catch (Exception ex)
{
if (ex is DataConsistencyException ||
ex is XmlException)
{
exBuilder.Clear();
exBuilder.Append(ex.Message + Environment.NewLine);
RichTextBox richTextBox = new RichTextBox();
richTextBox.Text = exBuilder;
richTextBox.Dock = DockStyle.Fill;
Form richMessageBox = new Form
{
StartPosition = FormStartPosition.CenterScreen,
ControlBox = true,
Text = "Error in File",
MaximizeBox = false,
MinimizeBox = false
};
richMessageBox.Controls.Add(richTextBox);
richMessageBox.ShowDialog();
return;
}
throw;
}
}
Run Code Online (Sandbox Code Playgroud) 我一直在互联网上搜索,但找不到任何帮助.我的问题是serialize一个arraylist到xml.我首先从数据库中收集数据并将其分配给arraylist,如下所示,
ArrayList conRc = new ArrayList();
while (readIp.Read())
{
string ipVal = readIp.GetString(0);
string conLvlVal = readIp.GetString(1);
string ispVal = readIp.GetString(2);
string tsVal = readIp.GetString(3);
ispVal = ispVal.Trim();
ispVal = ispVal.Replace("\"", "");
string localPortVal = readIp.GetString(4);
string foeriegnGeoVal = readIp.GetString(5);
conRc.Add(new Confidence(tsVal, ipVal, localPortVal, ispVal, foeriegnGeoVal, conLvlVal));
}
Run Code Online (Sandbox Code Playgroud)
并尝试按如下方式序列化arraylist,
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ArrayList));
System.IO.TextWriter writer = new System.IO.StreamWriter(@"F:\myItems.xml", false);
serializer.Serialize(writer, conRc);
writer.Close();
Run Code Online (Sandbox Code Playgroud)
但我得到一个错误说,
There was an error generating the XML document.
我可以知道如何执行这项任务......这将是一个很好的帮助.
仅供参考,下面是 …
我在填写DataGrid数据时遇到问题.这是我的代码,用于反序列化XML file并将信息放入数组中,然后将其Array放入DataGrid使用ItemsSource方法中.
public partial class Teacher_Page : Window
{
List<User> pupils;
public Teacher_Page()
{
InitializeComponent();
XmlSerializer deserializer = new XmlSerializer(typeof(List<User>));
TextReader textReader = new StreamReader("../../../Pupils.xml");
pupils = (List<User>)deserializer.Deserialize(textReader);
textReader.Close();
lbtest.Content = pupils[2].Name;
dataResults.ItemsSource = pupils;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行程序时,我DataGrid会填充正确的行数,arraylist但是行是空的并且没有列.lbltest从中输出一个字符串arraylist来证明它arraylist不是空的,这是正确的.
AutoGenerateColumns也设置为true.
XAML
<DataGrid x:Name="dataResults" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="248" Width="610" IsReadOnly="True"/>
Run Code Online (Sandbox Code Playgroud)
Code behind
public class User
{
public String Name;
public int …Run Code Online (Sandbox Code Playgroud)