无法使用 XElement 加载带有重音字符的文件
本文关键字:字符 文件 XElement 加载 | 更新日期: 2023-09-27 17:57:03
我尝试以下代码,但它无法正常工作,请有任何想法。
string file = @"C:'Program.xml";
XElement root = XElement.Parse(File.ReadAllText(file).Replace("'"", "'"));
XML文件的示例:
<?xml version="1.0" encoding="UTF-8"?>
<session xmlns="http://winscp.net/schema/session/1.0" name="test" start="2014-04-04T15:54:09.728Z">
<upload>
<filename value="D:'ftp'test2.TXT" />
<destination value="/in/test2.TXT" />
<result success="true" />
</upload>
<touch>
<filename value="/in/test2.TXT" />
<modification value="2014-03-27T12:45:20.000Z" />
<result success="false" />
</touch>
</session>
我需要使用XElement进行进一步治疗
我想你有点困惑
Xdocument xdoc=Xdocument.Load(filepath);
这就是您所需要的,您可以使用 XML 移动而不会出现任何问题
xdoc.root.elements("nameElement").Attributes("nameAttribute").Value
等等。
这真的很简单:)
这里有一个简单的例子:在VBNet中,然后在C#中。假设您有一个简单的网页,其中包含一个带有其事件的按钮
Protected Sub btnGetValues_Click(sender As Object, e As EventArgs) Handles btnGetValues.Click
Dim xdoc As XDocument = XDocument.Load(Server.MapPath("~/data.xml"))
Dim ns As XNamespace = "http://winscp.net/schema/session/1.0"
Dim Sb As New StringBuilder
Try
'iterate within xmlelement where assume with this code that "session" is root
'and descendant are upload and its child and touch with its childs
For Each el In (From a In xdoc.Root.Descendants(ns + "upload") Select a)
For Each subelement In el.Descendants
Response.Write("<b>" & subelement.Name.ToString & "</b><ul>")
If subelement.HasAttributes Then
For Each att In subelement.Attributes
Response.Write("<li>" & att.Name.ToString & ":" & att.Value.ToString & "</li>")
Next
End If
Response.Write("</ul>")
Next
Next
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
C# 版本:
protected void btnGetValues_Click(object sender, EventArgs e)
{
XDocument xdoc = XDocument.Load(Server.MapPath("~/data.xml"));
XNamespace ns = "http://winscp.net/schema/session/1.0";
StringBuilder Sb = new StringBuilder();
try {
//iterate within xmlelement where assume with this code that "session" is root
//and descendant are upload and its child and touch with its childs
foreach (object el_loopVariable in (from a in xdoc.Root.Descendants(ns + "upload")a)) {
el = el_loopVariable;
foreach (object subelement_loopVariable in el.Descendants) {
subelement = subelement_loopVariable;
Response.Write("<b>" + subelement.Name.ToString + "</b><ul>");
if (subelement.HasAttributes) {
foreach (object att_loopVariable in subelement.Attributes) {
att = att_loopVariable;
Response.Write("<li>" + att.Name.ToString + ":" + att.Value.ToString + "</li>");
}
}
Response.Write("</ul>");
}
}
} catch (Exception ex) {
Response.Write(ex.Message);
}
}
这是在页面作为响应.write的结果:
{http://winscp.net/schema/session/1.0}文件名
- 值:D:''ftp''test2.TXT
- in/test2.TXT
- success:true