带命名空间的XML文件的节点添加

C# Code:

string xmlPath = "D:\\test.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
// Save namespace uri
string msoUri = "http://schemas.microsoft.com/office/2009/07/customui";
// Set new namespace
XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable);
xnm.AddNamespace("mso", msoUri);
XmlNode root = xmlDoc.SelectSingleNode("mso:customUI", xnm);
XmlElement rootElement = (XmlElement)root;
rootElement.SetAttribute("xmlns:x1", "ns.iStamp");
rootElement.SetAttribute("xmlns:x2", "mhbAddin.Connect");

XmlNode node = xmlDoc.SelectSingleNode("mso:customUI/mso:ribbon/mso:tabs", xnm);
// Create "mso:tabs"
if (node == null)
{
    XmlNode ribbon = xmlDoc.SelectSingleNode("mso:customUI/mso:ribbon", xnm);
    XmlElement tabs = xmlDoc.CreateElement("mso", "tabs", msoUri);
    ribbon.AppendChild(tabs);
    node = xmlDoc.SelectSingleNode("mso:customUI/mso:ribbon/mso:tabs", xnm);
}

// Create "mso:tab" and "mso:group"
XmlElement tabx1 = xmlDoc.CreateElement("mso", "tab", msoUri);
tabx1.SetAttribute("idQ", "x1:LegacyIDRemover");
tabx1.SetAttribute("visible", "false");
XmlElement group1 = xmlDoc.CreateElement("mso", "group", msoUri);
group1.SetAttribute("idQ", "x1:grRemoveLegacyID");
group1.SetAttribute("visible", "false");
tabx1.AppendChild(group1);
node.AppendChild(tabx1);

XmlElement tabx2 = xmlDoc.CreateElement("mso", "tab", msoUri);
tabx2.SetAttribute("idQ", "x2:esqTab");
XmlElement group2 = xmlDoc.CreateElement("mso", "group", msoUri);
group2.SetAttribute("x1", "grRemoveLegacyID");
tabx2.AppendChild(group2);
node.AppendChild(tabx2);

// Save to file
xmlDoc.Save(xmlPath);

test.xml(结果):

<mso:customUI xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui" xmlns:x1="ns.iStamp" xmlns:x2="mhbAddin.Connect">
  <mso:ribbon>
    <mso:tabs>
      <mso:tab idQ="x1:LegacyIDRemover" visible="false">
        <mso:group idQ="x1:grRemoveLegacyID" visible="false" />
      </mso:tab>
      <mso:tab idQ="x2:esqTab">
        <mso:group x1="grRemoveLegacyID" />
      </mso:tab>
    </mso:tabs>
  </mso:ribbon>
</mso:customUI>
posted @ 2019-02-20 14:04  Kyle0418  阅读(858)  评论(0编辑  收藏  举报