这里我有一个动态创建xml文件的场景,它应该是可序列化的。 xml就像:
<person>
<personaldata>
<name>gopi</name>
<lastname>ch</lastname>
</personaladata>
<Educationaladata>
<Graduation>b.tech</graduation>
<designation>Engineer</designation>
</educationaldata>
</person>
人类具有姓名,姓氏,名称,毕业和财产
我试过这个
public string CreateXmlObject(Person objPerson)
{
var objXmlDocument = new XmlDocument();
var objXpath = objXmlDocument.CreateNavigator();
var objXmlSeialiser = new XmlSerializer(objPerson.GetType());
using (var xs = objXpath.AppendChild())
{
objXmlSeialiser.Serialize(xs, objPerson);
}
return objXmlDocument.OuterXml;
}
我的问题是我必须从Xml读取特定数据并将特定数据更新到Xml。我想在更新时只阅读Personaldata
,更新应仅适用于Personaldata
不Otherdata
答案 0 :(得分:2)
所有XML的Fisrt都无效,所有节点都应与其结束标记匹配。考虑到您的Intent
类看起来像这样: -
person
您可以使用public class Person
{
public string name { get; set; }
public string lastname { get; set; }
public string Graduation { get; set; }
public string designation { get; set; }
}
轻松完成: -
LINQ-to-XML
答案 1 :(得分:2)
试试xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string name = "gopi";
string lastname = "ch";
string graduation = "b.tech";
string designation = "Engineer";
XElement personalData = new XElement("person", new XElement[] {
new XElement("personaldata", new XElement[] {
new XElement("name", name),
new XElement("lastname", lastname)
}),
new XElement("Educationadata", new XElement[] {
new XElement("Graduation", graduation),
new XElement("designation", designation)
})
});
}
}
}
答案 2 :(得分:0)
sSometing like -
var xml = XDocument.Load("xml path");
var personaldata = xml.Descendents("personaldata").FirstOrDefault();
if (data != null)
{
foreach (var t in data.Descendants())
{
t.Value = "test";
}
}