none
Create XML element with prefix but no xmlns attribute? RRS feed

  • Question

  • Is there a way to create this XML with the .NET XML namespace methods? The elements below <fld2> are namespace qualified

    <root>
      <fld1>
      </fld1>
      <fld2 xmlns:tjh="http://test.com">
        <tjh:fld3>stuff</tjh:fld3>
        <tjh:fld4>stuff</tjh:fld4>
      </fld2>
    </root>

    When I use
    XmlElement fld = xDoc.CreateElement("tjh:fld2");
    -or-
    XmlElement fld = xDoc.CreateElement("tjh:fld2", "");
    -or-
    XmlElement fld= xDoc.CreateElement("tjh", "fld2", null);
    -or-
    XmlElement fld= xDoc.CreateElement("tjh", "fld2", "");

    fld.prefix is 'tjh'
    fld.Name is 'tjh:fld2'
    However fld.OuterXml generates <fld2/> the prefix is not present


    When I use
    XmlElement fld = xDoc.CreateElement("tjh:fld2", "http://test.com")
    -or-
    XmlElement fld= xDoc.CreateElement("tjh", "fld2", "http://test.com");
    fld.OuterXml generates "<tjh:fld2 xmlns:tjh=\"http://test.com\" />"; The prefix is present, but the extraneous xmlns attribute is applied to every element in the document.  Since the xmlns is declared on the parent node, I don't think it needs to be emitted on all the child nodes?


    Friday, April 11, 2014 9:20 PM

Answers

  • Hi, below is the sample code to create the xml file you want:

    XmlDocument xDoc = new XmlDocument();
    xDoc.PreserveWhitespace = false;
    
    XmlElement root = xDoc.CreateElement("root");
    XmlElement fld1 = xDoc.CreateElement("fld1");
    XmlElement fld2 = xDoc.CreateElement("tjh", "fld2", "http://test.com");
    XmlElement fld3 = xDoc.CreateElement("tjh", "fld3", "http://test.com");
    fld3.InnerText = "stuff";
    XmlElement fld4 = xDoc.CreateElement("tjh", "fld4", "http://test.com");
    fld4.InnerText = "stuff";
    
    xDoc.AppendChild(root);
    root.AppendChild(fld1);
    root.AppendChild(fld2);
    fld2.AppendChild(fld3);
    fld2.AppendChild(fld4);
    
    xDoc.Save(@"D:\test.xml");

    Saturday, April 12, 2014 10:18 AM

All replies

  • You have a Node <Root>, Elements <fld1>, and Attributes "stuff".

    jdweng

    Saturday, April 12, 2014 4:12 AM
  • Hi, below is the sample code to create the xml file you want:

    XmlDocument xDoc = new XmlDocument();
    xDoc.PreserveWhitespace = false;
    
    XmlElement root = xDoc.CreateElement("root");
    XmlElement fld1 = xDoc.CreateElement("fld1");
    XmlElement fld2 = xDoc.CreateElement("tjh", "fld2", "http://test.com");
    XmlElement fld3 = xDoc.CreateElement("tjh", "fld3", "http://test.com");
    fld3.InnerText = "stuff";
    XmlElement fld4 = xDoc.CreateElement("tjh", "fld4", "http://test.com");
    fld4.InnerText = "stuff";
    
    xDoc.AppendChild(root);
    root.AppendChild(fld1);
    root.AppendChild(fld2);
    fld2.AppendChild(fld3);
    fld2.AppendChild(fld4);
    
    xDoc.Save(@"D:\test.xml");

    Saturday, April 12, 2014 10:18 AM