使用XmlDocument而不是XElement
答案 0 :(得分:0)
不太清楚是什么让您选择XmlDocument
而不是Linq
到Xml
。如果有选择,我更喜欢使用XDocument
来处理Xml
。
无论如何,您可以使用XmlDocument
执行此操作。
public static string Stringify(XmlDocument doc)
{
StringBuilder result = new StringBuilder();
result.Append("ID=");
foreach(XmlElement element in doc.GetElementsByTagName("var_name"))
{
result.Append(element.GetAttribute("name"));
foreach(XmlElement child in element.ChildNodes)
{
result.Append(string.Format(" {0}={1}", child.GetAttribute("ns"), child.GetAttribute("ps")));
}
}
return result.ToString();
}
<强>输出继电器:强>
ID=name1 Desc=0 otp=0
选中此example
答案 1 :(得分:0)
试试这个......
Usings
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
类
[XmlRoot(ElementName = "p")]
public class P
{
[XmlAttribute(AttributeName = "ns")]
public string Ns { get; set; }
[XmlAttribute(AttributeName = "ps")]
public string Ps { get; set; }
}
[XmlRoot(ElementName = "var_name")]
public class Var_name
{
[XmlElement(ElementName = "p")]
public List<P> P { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
}
[XmlRoot(ElementName = "msg")]
public class Msg
{
[XmlElement(ElementName = "var_name")]
public Var_name Var_name { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
代码
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("xml.xml");
string XML = xmlDoc.InnerXml.ToString();
byte[] BUFXML = ASCIIEncoding.UTF8.GetBytes(XML);
MemoryStream ms1 = new MemoryStream(BUFXML);
XmlSerializer DeserializerPlaces = new XmlSerializer(typeof(Msg));
using (XmlReader reader = new XmlTextReader(ms1))
{
Msg dezerializedXML = (Msg)DeserializerPlaces.Deserialize(reader);
}// Put a break-point here, then mouse-over dezerializedXML and you should have you values
}
catch (System.Exception)
{
throw;
}
}
}
该代码将获取您的xml(从与应用程序* .exe相同的文件夹中的xml.xml文件中读入)然后将其序列化为名为“dezerializedXML”的对象..... p>