在调试时,新创建的元素的前缀为w :,但最后的Xmldoc会丢失它。
以下元素的结果InnerXML是:
<altChunk id="FF_HTML" xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main" />
预期结果为<w:altChunk r:id="FF_HTML"/>
private static XmlDocument prepareHTMLChunks(PackagePart partDocumentXML)
{
XmlDocument doc = new XmlDocument();
Stream xmlStream = partDocumentXML.GetStream();
doc.Load(xmlStream);
NameTable nt = new NameTable();
nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
XmlNodeList nodeList = doc.SelectNodes("//w:bookmarkStart", nsManager);
foreach (XmlNode node in nodeList)
{
foreach (XmlAttribute attr in node.Attributes)
{
if (attr.Value.EndsWith("HTML"))
{
//XmlElement el = doc.CreateElement("w","w:altChunk",string.Empty);
XmlElement el = doc.CreateElement("altChunk",nsManager.LookupNamespace("w"));
XmlAttribute altChunkAttr = doc.CreateAttribute("r","id",string.Empty);
altChunkAttr.Prefix = "r";
altChunkAttr.Value = attr.Value;
el.SetAttributeNode(altChunkAttr);
XmlNode nodeToReplace = node.ParentNode;
XmlNode bodyNode = doc.SelectSingleNode("//w:body", nsManager);
bodyNode.ReplaceChild(el, nodeToReplace);
}
}
}
return doc;
}
答案 0 :(得分:1)
前缀只是命名空间的别名。前缀本身并不重要。如果你愿意,你可以使用“前缀”作为前缀,这意味着完全相同的事情。
同样,完全相同的结果可能来自您在问题中显示的xmlns =“...”。这意味着与“w:”前缀完全相同,假设“w”别名为同一名称空间。
答案 1 :(得分:0)
好的,我修好了:
private static XmlDocument prepareHTMLChunks(PackagePart partDocumentXML)
{
XmlDocument _document = new XmlDocument();
Stream xmlStream = partDocumentXML.GetStream();
_document.Load(xmlStream);
XmlNamespaceManager _ns = new XmlNamespaceManager(_document.NameTable);
_ns.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
XmlNode _body = _document.SelectSingleNode("//w:body", _ns);
foreach (XmlNode _node in _document.SelectNodes("//w:bookmarkStart", _ns))
{
foreach (XmlAttribute _attribute in _node.Attributes)
{
if (_attribute.Value.EndsWith("HTML"))
{
XmlElement _element = _document.CreateElement("w", "altChunk", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
XmlAttribute _newAttr = _document.CreateAttribute("r", "id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
_newAttr.Value = _attribute.Value;
_element.Attributes.Append(_newAttr);
_body.AppendChild(_element);
}
}
}
return _document;
}