Add Namespaces with XmlTextReader and XmltextWriter? - DOTNET

This is a discussion on Add Namespaces with XmlTextReader and XmltextWriter? - DOTNET ; Framework 1.1, I have an existing complex XML document. I need to add some namespace information to certain elements. Can anyone illustrate how to use and XmlTextReader and XmlTextWriter to add custom namespace info where I want it? Thanks....

+ Reply to Thread
Results 1 to 4 of 4

Add Namespaces with XmlTextReader and XmltextWriter?

  1. Default Add Namespaces with XmlTextReader and XmltextWriter?

    Framework 1.1, I have an existing complex XML document. I need to add
    some namespace information to certain elements. Can anyone illustrate
    how to use and XmlTextReader and XmlTextWriter to add custom namespace
    info where I want it?

    Thanks.


  2. Default RE: Add Namespaces with XmlTextReader and XmltextWriter?

    Hi Lucius,

    Nice to see you and how are you doing?

    Regarding on the question about add namespace into certain element in XML
    document, here are some of my understanding and suggestion:

    ** If it possible to use XML Document? If so, you can simply load the xml
    document into memory and add the namespace as an xmlattribute onto the
    certain element. e.g.

    =====================
    static void RunDOM()
    {
    XmlDocument doc = new XmlDocument();
    doc.Load(@"..\..\data.xml");



    Console.WriteLine(doc.OuterXml);

    XmlElement rootelm = doc.DocumentElement;

    XmlAttribute attr = doc.CreateAttribute("xmlns", "myns",
    "http://www.w3.org/2000/xmlns/");
    attr.Value = "http://mytest.org/testxml";

    rootelm.Attributes.Append(attr);


    Console.WriteLine("\r\n\r\n\r\n\r\n") ;


    Console.WriteLine(doc.OuterXml);

    }

    this would be simple and convenient and work well as long as the xml
    document is not quite large.



    ** For xmlreader/ xmlwriter approach, you can first write out xml nodes
    while reading from XmlReader(in a while loop) and do some
    customziation(such as insert attributes) whenever the xmlreader arrive the
    node you want. Here is a test code snippet demonstrate this:

    =========================================

    static void RunReaderWriter()
    {
    XmlTextReader xtr = new XmlTextReader(
    new StreamReader(@"..\..\data.xml", Encoding.UTF8)
    );

    XmlTextWriter xtw = new XmlTextWriter("output1.xml",
    Encoding.UTF8);

    while (xtr.Read())
    {


    if (xtr.IsStartElement() && xtr.NodeType ==
    XmlNodeType.Element && xtr.LocalName == "PurchaseOrder")
    {
    Console.WriteLine("here come the 'PurchaseOrder'
    element.");

    //add new namespace attr
    xtw.WriteStartElement(xtr.Prefix, xtr.LocalName,
    xtr.NamespaceURI);
    xtw.WriteAttributeString(
    "xmlns", "myns", "http://www.w3.org/2000/xmlns/",
    "http://mytest.org/testxml"
    );

    //copy existing attrs
    xtw.WriteAttributes(xtr, true);

    }
    else
    {


    xtw.WriteNode(xtr, true);
    }
    }

    xtr.Close();
    xtw.Close();
    }

    =====================================

    and below is the test xml document for your reference
    =====================================

    <?xml version="1.0" encoding="utf-8" ?>
    <PurchaseOrder>
    <Number>1001</Number>
    <OrderDate>8/12/01</OrderDate>
    <BillToAddress>
    <Street>101 Main Street</Street>
    <City>Charlotte</City>
    <State>NC</State>
    <ZipCode>28273</ZipCode>
    </BillToAddress>
    <ShipToAddress>
    <Street>101 Main Street</Street>
    <City>Charlotte</City>
    <State>NC</State>
    <ZipCode>28273</ZipCode>
    </ShipToAddress>
    <LineItem Name="Computer Desk" Description="Wood desk for computer"
    SKU="12345A123" Price="499.99" Qty="1" />
    </PurchaseOrder>

    ============================

    Hope this helps.

    Sincerely,

    Steven Cheng

    Microsoft MSDN Online Support Lead



    ==================================================

    Get notification to my posts through email? Please refer to
    http://msdn.microsoft.com/subscripti...ult.aspx#notif
    ications.



    Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
    where an initial response from the community or a Microsoft Support
    Engineer within 1 business day is acceptable. Please note that each follow
    up response may take approximately 2 business days as the support
    professional working with you may need further investigation to reach the
    most efficient resolution. The offering is not appropriate for situations
    that require urgent, real-time or phone-based interactions or complex
    project ****ysis and dump ****ysis issues. Issues of this nature are best
    handled working with a dedicated Microsoft Support Engineer by contacting
    Microsoft Customer Support Services (CSS) at
    http://msdn.microsoft.com/subscripti...t/default.aspx.

    ==================================================


    This posting is provided "AS IS" with no warranties, and confers no rights.




  3. Default Re: Add Namespaces with XmlTextReader and XmltextWriter?

    In article <4meoc3hr3btskdpjiuh8rt1123k7u9liv2@4ax.com>, Lucius wrote:
    > Framework 1.1, I have an existing complex XML document. I need to add
    > some namespace information to certain elements. Can anyone illustrate
    > how to use and XmlTextReader and XmlTextWriter to add custom namespace
    > info where I want it?


    Here's a C# test program that I used to handle existing XML with
    non-default namespaces.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.Xml.XPath;
    using log4net;
    using log4net.Config;
    using System.IO;
    using System.Threading;


    // Configure log4net using the .config file
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]

    namespace csXml
    {
    public partial class Form1 : Form
    {
    // Define a static logger variable so that it references the
    // Logger instance named "MyApp".
    private static readonly ILog log =
    LogManager.GetLogger(typeof(Form1));

    NameTable nt;
    XmlNamespaceManager nsmgr;
    XmlParserContext context;

    public Form1()
    {
    InitializeComponent();

    log.Info(String.Format(DateTime.Now.ToString("hh:mm:ss.fff")
    + " Main Thread id: {0}", Thread.CurrentThread.ManagedThreadId));

    }

    private void button1_Click(object sender, EventArgs e)
    {
    try
    {
    display.Text = "";
    string filename =
    @"C:\prof\computing\experimenting\PowerShell\testFragments.xml";
    StreamReader str = new StreamReader(filename);
    string srtext = str.ReadToEnd();

    nt = new NameTable();
    nsmgr = new XmlNamespaceManager(nt);
    nsmgr.AddNamespace("log4j",
    "http://jakarta.apache.org/log4j");
    context = new XmlParserContext(nt, nsmgr, "log4j:event",
    null, null, null, null, null, XmlSpace.None);
    XmlTextReader xr = new XmlTextReader(srtext,
    XmlNodeType.Element, context);
    XmlNodeType xrm = xr.MoveToContent();
    while (xr.EOF != true)
    {
    XmlReader xsr = xr.ReadSubtree();
    xrm = xsr.MoveToContent();
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(xsr);
    XmlNodeList nodel =
    xmldoc.SelectNodes("log4j:event/log4j:message/text()", nsmgr);
    foreach (XmlNode node in nodel)
    {
    display.Text = display.Text + node.OuterXml +
    Environment.NewLine;
    }
    xrm = xr.NodeType;
    if (xrm == XmlNodeType.EndElement) // if
    we're on the end element (of the previous subtree)
    {
    xr.Read(); // read past the end
    element
    xrm = xr.MoveToContent(); // advance to the
    next content node
    }
    }

    }
    catch (Exception exc)
    {
    string errText = String.Format("Exception while opening
    file: {0}", exc.ToString());
    MessageBox.Show(errText);
    log.Error(errText);
    return;
    }
    }
    }
    }

    Hope this helps.

    Mike


  4. Default RE: Add Namespaces with XmlTextReader and XmltextWriter?

    Hi Lucius,

    Have you got any further idea on this or does the suggestion in my last
    reply help some?

    Please feel free to let me know if there is anything else need help.

    Sincerely,

    Steven Cheng

    Microsoft MSDN Online Support Lead


    This posting is provided "AS IS" with no warranties, and confers no rights.


    --------------------
    >X-Tomcat-ID: 45013291
    >References: <4meoc3hr3btskdpjiuh8rt1123k7u9liv2@4ax.com>
    >MIME-Version: 1.0
    >Content-Type: text/plain
    >Content-Transfer-Encoding: 7bit
    >From: stcheng@online.microsoft.com (Steven Cheng[MSFT])
    >Organization: Microsoft
    >Date: Thu, 23 Aug 2007 04:17:04 GMT
    >Subject: RE: Add Namespaces with XmlTextReader and XmltextWriter?
    >X-Tomcat-NG: microsoft.public.dotnet.framework
    >Message-ID: <kqOQ#xT5HHA.360@TK2MSFTNGHUB02.phx.gbl>
    >Newsgroups: microsoft.public.dotnet.framework
    >Lines: 114
    >Path: TK2MSFTNGHUB02.phx.gbl
    >Xref: TK2MSFTNGHUB02.phx.gbl microsoft.public.dotnet.framework:8352
    >NNTP-Posting-Host: tomcatimport2.phx.gbl 10.201.218.182
    >
    >Hi Lucius,
    >
    >Nice to see you and how are you doing?
    >
    >Regarding on the question about add namespace into certain element in XML
    >document, here are some of my understanding and suggestion:
    >
    >** If it possible to use XML Document? If so, you can simply load the xml
    >document into memory and add the namespace as an xmlattribute onto the
    >certain element. e.g.
    >
    >=====================
    > static void RunDOM()
    > {
    > XmlDocument doc = new XmlDocument();
    > doc.Load(@"..\..\data.xml");
    >
    >
    >
    > Console.WriteLine(doc.OuterXml);
    >
    > XmlElement rootelm = doc.DocumentElement;
    >
    > XmlAttribute attr = doc.CreateAttribute("xmlns", "myns",
    >"http://www.w3.org/2000/xmlns/");
    > attr.Value = "http://mytest.org/testxml";
    >
    > rootelm.Attributes.Append(attr);
    >
    >
    > Console.WriteLine("\r\n\r\n\r\n\r\n") ;
    >
    >
    > Console.WriteLine(doc.OuterXml);
    >
    >}
    >
    >this would be simple and convenient and work well as long as the xml
    >document is not quite large.
    >
    >
    >
    >** For xmlreader/ xmlwriter approach, you can first write out xml nodes
    >while reading from XmlReader(in a while loop) and do some
    >customziation(such as insert attributes) whenever the xmlreader arrive the
    >node you want. Here is a test code snippet demonstrate this:
    >
    >=========================================
    >
    > static void RunReaderWriter()
    > {
    > XmlTextReader xtr = new XmlTextReader(
    > new StreamReader(@"..\..\data.xml", Encoding.UTF8)
    > );
    >
    > XmlTextWriter xtw = new XmlTextWriter("output1.xml",
    >Encoding.UTF8);
    >
    > while (xtr.Read())
    > {
    >
    >
    > if (xtr.IsStartElement() && xtr.NodeType ==
    >XmlNodeType.Element && xtr.LocalName == "PurchaseOrder")
    > {
    > Console.WriteLine("here come the 'PurchaseOrder'
    >element.");
    >
    > //add new namespace attr
    > xtw.WriteStartElement(xtr.Prefix, xtr.LocalName,
    >xtr.NamespaceURI);
    > xtw.WriteAttributeString(
    > "xmlns", "myns", "http://www.w3.org/2000/xmlns/",
    > "http://mytest.org/testxml"
    > );
    >
    > //copy existing attrs
    > xtw.WriteAttributes(xtr, true);
    >
    > }
    > else
    > {
    >
    >
    > xtw.WriteNode(xtr, true);
    > }
    > }
    >
    > xtr.Close();
    > xtw.Close();
    > }
    >
    >=====================================
    >
    >and below is the test xml document for your reference
    >=====================================
    >
    ><?xml version="1.0" encoding="utf-8" ?>
    ><PurchaseOrder>
    > <Number>1001</Number>
    > <OrderDate>8/12/01</OrderDate>
    > <BillToAddress>
    > <Street>101 Main Street</Street>
    > <City>Charlotte</City>
    > <State>NC</State>
    > <ZipCode>28273</ZipCode>
    > </BillToAddress>
    > <ShipToAddress>
    > <Street>101 Main Street</Street>
    > <City>Charlotte</City>
    > <State>NC</State>
    > <ZipCode>28273</ZipCode>
    > </ShipToAddress>
    > <LineItem Name="Computer Desk" Description="Wood desk for computer"
    > SKU="12345A123" Price="499.99" Qty="1" />
    ></PurchaseOrder>
    >
    >============================
    >
    >Hope this helps.
    >
    >Sincerely,
    >
    >Steven Cheng
    >
    >Microsoft MSDN Online Support Lead
    >
    >
    >
    >==================================================
    >
    >Get notification to my posts through email? Please refer to
    >http://msdn.microsoft.com/subscripti...ault.aspx#noti

    f
    >ications.
    >
    >
    >
    >Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
    >where an initial response from the community or a Microsoft Support
    >Engineer within 1 business day is acceptable. Please note that each follow
    >up response may take approximately 2 business days as the support
    >professional working with you may need further investigation to reach the
    >most efficient resolution. The offering is not appropriate for situations
    >that require urgent, real-time or phone-based interactions or complex
    >project ****ysis and dump ****ysis issues. Issues of this nature are best
    >handled working with a dedicated Microsoft Support Engineer by contacting
    >Microsoft Customer Support Services (CSS) at
    >http://msdn.microsoft.com/subscripti...t/default.aspx.
    >
    >==================================================
    >
    >
    >This posting is provided "AS IS" with no warranties, and confers no rights.
    >
    >
    >
    >



+ Reply to Thread

Similar Threads

  1. using XmlTextWriter
    By Application Development in forum XML SOAP
    Replies: 1
    Last Post: 03-05-2007, 09:48 AM
  2. How to create this with XmlTextWriter
    By Application Development in forum XML SOAP
    Replies: 2
    Last Post: 11-09-2006, 06:00 AM
  3. XmlTextWriter.WriteString
    By Application Development in forum XML SOAP
    Replies: 2
    Last Post: 09-08-2006, 05:54 AM
  4. XMLTextWriter and SOAP
    By Application Development in forum XML SOAP
    Replies: 1
    Last Post: 04-03-2006, 12:59 PM
  5. xmlTextWriter
    By Application Development in forum XML SOAP
    Replies: 5
    Last Post: 04-03-2006, 12:07 PM