Add Namespaces with XmlTextReader and XmltextWriter?

  • Thread starter Thread starter lucius
  • Start date Start date
L

lucius

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.
 
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/subscriptions/managednewsgroups/default.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 analysis and dump analysis 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/subscriptions/support/default.aspx.

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


This posting is provided "AS IS" with no warranties, and confers no rights.
 
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
 
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: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
From: (e-mail address removed) (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#[email protected]>
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/subscriptions/managednewsgroups/default.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 analysis and dump analysis 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/subscriptions/support/default.aspx.

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


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