这是一个代码示例:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
...
static void Main()
{
Person[] persons = new Person[]
{
new Person{ FirstName = "John", LastName = "Smith"},
new Person{ FirstName = "Mark", LastName = "Jones"},
new Person{ FirstName= "Alex", LastName="Hackman"}
};
XmlSerializer xs = new XmlSerializer(typeof(Person[]), "");
using (FileStream stream = File.Create("persons-" + Guid.NewGuid().ToString().Substring(0, 4) + ".xml"))
{
xs.Serialize(stream, persons);
}
}
这是输出:
<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>
<Person>
<FirstName>Mark</FirstName>
<LastName>Jones</LastName>
</Person>
<Person>
<FirstName>Alex</FirstName>
<LastName>Hackman</LastName>
</Person>
</ArrayOfPerson>
这是一个问题。如何摆脱根元素并呈现这样的人:
<?xml version="1.0"?>
<Person>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>
<Person>
<FirstName>Mark</FirstName>
<LastName>Jones</LastName>
</Person>
<Person>
<FirstName>Alex</FirstName>
<LastName>Hackman</LastName>
</Person>
谢谢!
答案 0 :(得分:5)
这是您想要的格式错误XML
,无法通过XmlSerializer
获取,但您可以将ArrayOfPersno
元素名称更改为其他内容:
示例:
XmlSerializer xs = new XmlSerializer(typeof(Person[]),
new XmlRootAttribute("Persons"));
会给你:
<?xml version="1.0"?>
<Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>
...
答案 1 :(得分:2)
IMO你应该使用顶级对象,即
[XmlRoot("whatever")]
public class Foo {
[XmlElement("Person")]
public List<Person> People {get;set;}
}
哪个应序列化为具有多个“Person”子元素的“whatever”元素。