将 XMLDocument 转换为 XDocument,获取名称空间 从 xsi 修改为 p1

Convert XMLDocument to XDocument ,getting names spaces Modifing from xsi to p1

我创建了一个 XMLDocument:

`

XmlDocument doc = new XmlDocument();
  XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
   // -----------------------create root-----------------------------  
                XmlElement rootnode = doc.CreateElement( "BMECAT");
                doc.InsertBefore(declaire, doc.DocumentElement);


                doc.AppendChild(rootnode);




                //Console.WriteLine(sb.ToString());
                //get attribute for BmeCat
                rootnode.SetAttribute("version", "2005");

                XmlAttribute atr = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");

                atr.Value = "http://www.adlnet.org/xsd/adlcp_v1p3";
                rootnode.SetAttributeNode(atr);
                rootnode.Attributes.Append(atr);`

然后我使用下面的函数将它转换为 XDocument,但我得到了一个像这样更改的 NameSpace

XDocument ToXDocument(XmlDocument xmlDocument)
{
    using (var nodeReader = new XmlNodeReader(xmlDocument))
    {
        nodeReader.MoveToContent();
        return XDocument.Load(nodeReader);
    }
}

`
在 xml 和 XDocument

下方

<?xml version="1.0" encoding="utf-8"?> <BMECAT version="2005" p1:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">

<?xml version="1.0" encoding="utf-8"?> <BMECAT version="2005" xsi:schemaLocation="http://www.adlnet.org/xsd/adlcp_v1p3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

您需要在元素的开头手动显式添加 xsi 命名空间声明。

节点按文档顺序处理,命名空间声明在首次使用后出现。它不知道使用 xsi 作为前缀,直到为时已晚。

var doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
var root = (XmlElement)doc.AppendChild(doc.CreateElement("BMECAT"));
var xsi = "http://www.w3.org/2001/XMLSchema-instance";
root.SetAttribute("xmlns:xsi", xsi); //set the namespace now
root.SetAttribute("schemaLocation", xsi, "http://www.adlnet.org/xsd/adlcp_v1p3");
root.SetAttribute("version", "2005");