Xname prefix incorrect RRS feed

  • Question

  • Hi I have been following some of Eric White's code to replace paragraph text. However, I have this code to create a copy of a Run but with different text, following on from how I understood Eric White was creating new XElements - though I've no doubt missed something 

    var firstEl = els.Elements.First(); 
    var el = new XElement(W.r, firstEl.Attributes(), firstEl.Elements().Where(e => e.Name != W.t), new XElement(W.t, "My new text here"));                

    I have referenced the OpenXmlPowerTools package hence I can provide W.r to the constructor. I had assumed that passing in the firstEl.Attributes would copy what I needed.

    But, if I look at the Xml for firstEl I see this

    <w:r xmlns:w="" w:rsidR="00B433E1">

    but if I look at my generated XElement I see

    -<r xmlns="" xmlns:p1="" p1:rsidR="00B433E1">
      <p1:t>"My new text here"</p1:t>

    As you can see instead of "w:r", I am just seeing "r" as the XName. I assume it is something to do with namespaces. Consequently when I include those xelement in my xdocument they are not appearing.

    Could you explain to me what i need to do so that I can replicate the namespace prefixes in my new XElement run. Many thx

    • Edited by Simon Woods Friday, October 25, 2019 2:30 PM more details
    Friday, October 25, 2019 2:21 PM

All replies

  • So I solved it by copying across the namespace info explicitly

    var firstEl = els.Elements.First();
    var ns = firstEl.Name.NamespaceName;
    var prefix = firstEl.GetPrefixOfNamespace(ns);
    var attrs = new List<XAttribute>(firstEl.Attributes());
    attrs.Add(new XAttribute(XNamespace.Xmlns + prefix, ns));                
    var el = new XElement(W.r, attrs, firstEl.Elements().Where(e => e.Name != W.t), new XElement(W.t, els.Bookmark.Value));   

    Friday, October 25, 2019 2:58 PM