我一直在尝试如何用XML创建数据库。我已经成功写了数据,如下所示:
<Employees>
<Worker>
<ID>1</ID>
<FirstName>Ilan</FirstName>
<LastName>Berlinbluv</LastName>
<Salary>5000</Salary>
</Worker>
</Employees>
问题在于,当我尝试使用此代码阅读时:
string writePath = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + @"\Desktop";
string writeFile = writePath + @"\Employees.xml";
using (XmlReader read = XmlReader.Create(writeFile))
{
while (read.Read())
{
if (read.IsStartElement())
{
Console.WriteLine("DEBUG: read.Name = {0}", read.Name);
Console.WriteLine("DEBUG: read.Value = {0}", read.Value);
switch (read.Name)
{
case "Employees":
Console.WriteLine("Start <Employees> master element");
break;
case "Employee":
Console.WriteLine("Start <Employee> element");
break;
case "Worker":
Console.WriteLine("Start <Worker> element");
break;
case "ID":
Console.WriteLine("Start reading <ID> element");
Console.WriteLine("Contains: " + read.Value.Trim());
break;
case "FirstName":
Console.WriteLine("Start reading <FirstName> element");
Console.WriteLine("Contains: " + read.Value.Trim());
break;
case "LastName":
Console.WriteLine("Start reading <LastName> element");
Console.WriteLine("Contains: " + read.Value.Trim());
break;
case "Salary":
Console.WriteLine("Start reading <Salary> element");
Console.WriteLine("Contains: " + read.Value.Trim());
break;
}
}
Console.ReadKey();
}
}
它没有正确读取值,只要它显示Start reading <Salary> element
然后Contains:
,它没有显示任何值,但应该有一个值:5000。这是语法错误,在哪里我需要它像:
<ID>
1
</ID>
我一直在做dotnetperls tutorial,但无济于事。
答案 0 :(得分:0)
不要尝试编写代码来读取XML文档。请改用内置的XML序列化程序。 http://msdn.microsoft.com/en-us/library/fa420a9y.aspx
答案 1 :(得分:0)
You can read XML like:
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("\\foldername\\" + "filename.xml"));
XmlNode node = doc.SelectSingleNode("//Employees//Worker/Salary");
Response.Write(node.InnerText.ToString());
This way, you can get 5000 as Salary.
答案 2 :(得分:0)
您可以使用XSD tool来使用序列化程序。首先创建XML模式,然后从XML模式创建一个类。然后,您可以直接将XML读取到对象:
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <exception cref="InvalidOperationException"></exception>
/// <returns></returns>
public static T Deserialize<T>(XmlNode xml)
{
// Assuming xml is an XML document containing a serialized object.
XmlNodeReader reader = new XmlNodeReader(xml);
// When we get the xml, it is usually a sub element that can have a different name, than the type name. Therefore look for the name
XmlSerializer ser = new XmlSerializer(typeof(T));
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
return (T)obj;
}
/// <summary>
/// Serializes without removing namespace and using the specified encoding
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="encoding"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">When the object can not be serialized to xml</exception>
public static XmlDocument Serialize<T>(T obj, Encoding encoding)
{
XmlSerializer ser = GetSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
using (XmlTextWriter writer = new XmlTextWriter(stream, encoding))
{
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
writer.Flush();
stream.Position = 0;
doc.Load(stream);
return doc;
}
}
您可能希望在创建类之前编辑XML架构,以确保类型正确。
答案 3 :(得分:0)
访问XML文件特定节点的最简单方法是使用LINQ。
string writePath = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + @"\Desktop";
string writeFile = writePath + @"\Employees.xml";
XDocument xmlDocument = XDocument.Load(writeFile)
然后如果你想阅读Worker元素中的所有元素
var queryResult = from x in xmlDocument.Root.Element("Worker").Elements() select x;
foreach (var item in queryResult)
{
Console.WriteLine(item.Value);
}
或者,如果您想要处理所有Worker元素separtelly,则只需将查询结果转换为列表
var queryResult = (from x in xmlDocument.Root.Element("Worker").Elements() select x).ToList();
Console.WriteLine("Start reading <ID> element");
Console.WriteLine("Contains: " + queryResult[0]);
Console.WriteLine("Start reading <FirstName> element");
Console.WriteLine("Contains: " + queryResult[1]);
Console.WriteLine("Start reading <LastName> element");
Console.WriteLine("Contains: " + queryResult[2]);
Console.WriteLine("Start reading <Salary> element");
Console.WriteLine("Contains: " + queryResult[3]);
答案 4 :(得分:0)
我发现在与业务对象进行序列化时,使用XML总是更容易。
[Serializable]
public class Employees
{
private List<Worker> _Workers;
[XmlArray]
public List<Worker> Workers
{
get { return _Workers; }
set { _Workers = value; }
}
}
[Serializable]
public class Worker
{
public Int32 ID { get; set; }
public String FirstName { get; set; }
// etc.
public void SerializeToXML(string outputFolderLocation)
{
try
{
if (!outputFolderLocation.EndsWith('\\'))
{
outputFolderLocation += "\\";
}
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof(Worker));
string outpath = outputFolderLocation + "FileName-" + DateTime.Now.ToBinary().ToString() + ".xml";
XmlTextWriter textWriter = new XmlTextWriter(outpath, Encoding.GetEncoding("ISO-8859-1"));
serializer.Serialize(textWriter, this, ns);
textWriter.Close();
}
catch (Exception ex)
{
throw new Exception("Error serializing to XML", ex);
}
}
}
您还可以通过创建值XML Attributes而不是节点来整理XML。要执行此操作,请将属性更改为:
[XmlAttribute("ID-Value")]
public Int32 ID { get; set; }
// would serialise like this <worker ID-Value="1"></worker>
答案 5 :(得分:0)
您需要使用read.InnerText而不是read.Value。
一旦你理解了所有这些是如何工作的,我建议使用内置的XML处理函数。你会为自己省去很多麻烦。