如何在C#中更改XmlDocument中的命名空间,如下所示。我可以用string.Replace更改innerxml。但有没有更好的方法来做到这一点。
<Result xmlns:Result="MyProject.Result">
<Result:Errors>
<Result:Error>
<Result:Severity>0</Result:Severity>
<Result:Reason>The input was wrong</Result:Reason>
</Result:Error>
</Result:Errors>
</Result>
<Result xmlns:Result="Project.User.Result">
<Result:Errors>
<Result:Error>
<Result:Severity>0</Result:Severity>
<Result:Reason>The input was wrong</Result:Reason>
</Result:Error>
</Result:Errors>
</Result>
答案 0 :(得分:0)
您可以通过使用允许此项的XmlSerializer-Overloads重写xml来更改命名空间。
public class Location { public string L; }
public class MyData { public Location[] Locations { get; set; } }
internal class Program
{
static void Main ()
{
// testdata
var m = new MyData { Locations = new Location[2] { new Location { L = "L1" }, new Location { L = "L2" } } };
// simple Serializer
var xs = new XmlSerializer (typeof (MyData));
DoSerialize (m, xs);
Console.WriteLine ();
var xs2 = new XmlSerializer (typeof (MyData), new XmlAttributeOverrides (), new Type[] { }, new XmlRootAttribute { Namespace = "MyNewNamspace" }, "");
DoSerialize (m, xs2);
Console.ReadLine ();
}
static void DoSerialize (MyData m, XmlSerializer xs)
{
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true,
NewLineOnAttributes = true
};
var sww = new System.IO.StringWriter ();
var writer = XmlWriter.Create (sww, settings);
xs.Serialize (writer, m);
Console.WriteLine (sww.ToString ().Replace ("><", ">\r\n<"));
}
}
答案 1 :(得分:0)
您可以尝试
((XmlElement)doc.FirstChild).SetAttribute("xmlns:Result", "Project.User.Result") ;