views:

793

answers:

2

I have this code for the settings:

Dim settings As XmlWriterSettings = New XmlWriterSettings()
            settings.Indent = True
            settings.OmitXmlDeclaration = True
            settings.NewLineOnAttributes = True

Then I have this code for the writer:

Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)

Please can you tell me how I make the settings apply to the writer?

Thanks a lot, Phil.

EDIT: Code sample

Sub writexml_OnClick(ByVal sender As Object, ByVal e As EventArgs)
    Try
        'Vars
        Dim securityid As String = Input_securityid.Text
        Dim enc As Encoding 

        Dim settings As XmlWriterSettings = New XmlWriterSettings()
        settings.Indent = True
        settings.OmitXmlDeclaration = True
        settings.NewLineOnAttributes = True
        settings.Encoding = enc

        'Declare the writer and set file name / settings
        Dim xml As XmlWriter = XmlWriter.Create(Server.MapPath("output.xml"), settings)

        'start document
        xml.WriteStartDocument()
        xml.WriteComment("")

        'start envelope
        xml.WriteStartElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/")
        'start body
        xml.WriteStartElement("soap", "Body", Nothing)
        xml.WriteAttributeString("xmlns", "ns1", Nothing, "http://its/foo.wsdl")

        'start biographical capture
        xml.WriteStartElement("ns1:biographicalcaptureElement")

        'start securityid
        xml.WriteStartElement("ns1:securityid")
        xml.WriteValue(securityid)
        'end securityid 
        xml.WriteEndElement()

        'start requestdata 
        xml.WriteStartElement("ns1:requestdata")

        'end requestdata
        xml.WriteEndElement()
        'end biographical capture
        xml.WriteEndElement()

        'end body
        xml.WriteEndElement()
        'end envelope
        xml.WriteEndElement()
        'end document 
        xml.WriteEndDocument()

        'clean up
        xml.Flush()
        xml.Close()

    Catch ex As Exception
        errorlbl.Text = ex.ToString
    Finally
        errorlbl.Text = ("Created file ok")
    End Try


    End Sub

It does work fine if I use;

Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)

the xml is produced but settings are not applied.

+2  A: 

This won't get you an XmlTextWriter, but to be honest I've always used XmlWriter when writing to a file anyway (XmlWriter is the base class of XmlTextWriter.)

You can use XmlWriter.Create(Server.MapPath("output.xml"), settings) which will give you an XmlWriter instead of an XmlTextWriter. Your encoding will then need to be set in your settings instance (settings.Encoding = enc.)

EDIT:

The sample code provided for me produces:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;
  <soap:Body xmlns:ns1="http://its/foo.wsdl" />
</soap:Envelope>

EDIT 2:

Your namespace is causing a problem because it's trying to put the element name as ns1:securityid when it should be the element name is securityid and the namespace ns1. You'll need to separate these like you've done in the WriteAttributeString call, like so:

instead of: xml.WriteStartElement("ns1:biographicalcaptureElement") use: xml.WriteStartElement("biographicalcaptureElement", "ns1")

With these changes in place I now get:

<!---->
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;
  <soap:Body xmlns:ns1="http://its/foo.wsdl"&gt;
    <biographicalcaptureElement xmlns="ns1">
      <securityid>TEST123</securityid>
      <requestdata />
    </biographicalcaptureElement>
  </soap:Body>
</soap:Envelope>
Andy Shellam
Thanks for the help Andy, much appreciated. I now have the code setup as you suggest, but when i try to generate the xml it comes back blank. Dim xml As XmlWriter = XmlWriter.Create(Server.MapPath("output.xml"), settings) Is that correct? Thanks
Phil
Yeah that looks right - can you edit your question and provide the relevant code sample?
Andy Shellam
Thanks, have added the code sample.
Phil
Can you add the rest of your code, showing you closing your elements and saving the document?
Andy Shellam
I've added to my answer what your sample code produces, which does seem to be taking your settings into account. Are you remembering to call xml.Close() after your writing?
Andy Shellam
Thanks Andy, I have added a slimmed down version of my code to the question. When I submit I still do not get an xml file. I get the success message only.
Phil
Right, because of the "finally", your exception is not being captured. Finally blocks get executed regardless of whether an exception occurred or not, so it's overwriting your exception label. If you remove your catch block you'll see the exception - which is the presence of a ":" character. See my edited answer for the resolution. Your success message should also go in the try block to make sure that if an exception occurs, you don't see that message.
Andy Shellam
ok i've edited the code as you said, and now getting:System.NullReferenceException: Object reference not set to an instance of an object. at System.Xml.XmlWriter.CreateWriterImpl(Stream output, Encoding encoding, Boolean closeOutput, XmlWriterSettings settings) at System.Xml.XmlWriter.Create(String outputFileName, XmlWriterSettings settings) at _Default.writexml_OnClick(Object sender, EventArgs e) in Default.aspx.vb:line 45
Phil
Line 45 is: Dim xml As XmlWriter = XmlWriter.Create(Server.MapPath("output.xml"), settings)
Phil
Either settings is null, or the result of Server.MapPath is null. Try hard-coding your path (e.g. Server.MapPath("C:\output.xml", settings)) to see if that's the culprit.
Andy Shellam
I'll try that now, Thanks so much for the detailed assistance you have been a real gent!
Phil
It maybe the culprit, as when I change it to C:\output.xml the error changes to: System.Web.HttpException: 'C:\output.xml' is not a valid virtual path. at System.Web.VirtualPath.Create(String virtualPath, VirtualPathOptions options) at System.Web.HttpServerUtility.MapPath(String path) at _Default.writexml_OnClick(Object sender, EventArgs e)
Phil
Andy your a legend its now working, the enc was returning null... Thanks a lot. If our paths ever cross I owe you several beers.
Phil
Not a problem Phil, glad I could help!
Andy Shellam
@Phil: undelete your deleted post. You were within seconds of getting an answer.
John Saunders
A: 

Vijay Bhaskar Semwal

public partial class XMLWriter : System.Web.UI.Page { static string strFileName=@"E:\vijay112.xml"; static XmlTextWriter write = null; public static int i = 0;

////// static string ProcessName=Process.GetCurrentProcess().ProcessName; //////static Process[] processes = Process.GetProcessesByName(ProcessName); ////// if ( // { ////// // Application.ExitThread(); ////// // }

    public XMLWriter()
    {

    }
    ~XMLWriter()
    {
        //write.Close(); ;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
                write = new XmlTextWriter(strFileName, null);

            div_div.InnerText = i.ToString();
        }
        catch (Exception ex)
        {
        }
    }

    public static string XMLWrite()
    {
        try
        {           

            if (i == 0)
                return "success";
            else
            {
                return "please end the"+i+"more child";
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        finally
        {
            try
            {

            }
            catch ( Exception ex){}
        }
    }

    public static void SetRootElement(string strRootElement)
    {
        write.WriteStartElement(strRootElement); 
    }
    //public static void SetAttributeString(string strRootElement)
    //{
       // write.WriteString();
    //}
    public static void SetChildElement(string strChildElement)
    {

        write.WriteStartElement(strChildElement);
    }
    public static void SetAttribute(string strAttribute, string strValue)
    {           
        write.WriteAttributeString(strAttribute, strValue);
    }
    public static void EndChildElement()
    {           
        write.WriteEndElement();

    }
    public static void EndRootElement()
    {            
        write.WriteFullEndElement();
    }

    protected void Bt_root_Click(object sender, EventArgs e)
    {
        SetRootElement(TB_key.Text);
    }
    protected void bt_child_Click(object sender, EventArgs e)
    {
        ++i;
        SetChildElement(TB_key.Text);

    }

    protected void BT_attribute_Click(object sender, EventArgs e)
    {
        SetAttribute(TB_key.Text, TB_value.Text);
    }

    protected void bt_endChild_Click(object sender, EventArgs e)
    {
                    --i; 
        EndChildElement();
    }

    protected void bt_endroot_Click(object sender, EventArgs e)
    {
        EndRootElement();
    }

    protected void bt_xml_Click(object sender, EventArgs e)
    {
        write.Close();
        XmlDocument xmldoc = new XmlDocument();
       xmldoc.Load(@"E:\vijay\SourceCodeBackEnd\PrimeroWebService\Images\vijay112.xml");
      //  write.Flush();
       Txml.Text= xmldoc.InnerXml;
    }

    protected void Txml_TextChanged(object sender, EventArgs e)
    {

    }
    protected void bt_close_Click(object sender, EventArgs e)
    {

    }

}
Vijay Bhaskar Semwal
how to creat xml document and display on text box we are taking 2 text box for input and five button for different purpose
Vijay Bhaskar Semwal