写一个非常样本的Xml文件 [英] Write a very sample Xml file

查看:94
本文介绍了写一个非常样本的Xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码 -

 XmlWriterSettings settings =  new  XmlWriterSettings(); 
settings.Indent = true ;
settings.IndentChars =( );
settings.CloseOutput = true ;
settings.OmitXmlDeclaration = true ;
使用(XmlWriter writer = XmlWriter.Create( books.xml,设置))
{
writer.WriteStartElement( );
writer.WriteElementString( title,book.Title);
writer.WriteElementString( author,book.Author.Name);
writer.WriteElementString( publisher,book.Publisher);
writer.WriteElementString( price,book.Price.ToString());
writer.WriteEndElement();
writer.Flush();
}


books.xml中的
输出是



 <书> 
.....
........
< / book>





但是我想要输出



< book key =A> 
....
...
...
< / book>





就这样。没有其他的。



怎么做?



添加的代码块,HTML编码 - OriginalGriff [/编辑]

解决方案

好吧,就像大多数计算机程序一样,它只会执行编码操作。如果要向元素添加属性,则需要在适当的位置添加代码。如果您不想要文件中的其他元素,则不要编写它们。 文档 [ ^ ]显示所有适当的方法详细信息。


< blockquote>假设您要将属性添加到 book 元素,请使用 XmlWriter.WriteAttributeString方法(字符串,字符串) [ ^ ]。



添加到您的代码中:

 writer.WriteAttributeString(  key  A); 


I use this code -

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" " );
settings.CloseOutput = true;
settings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create("books.xml" , settings))
    {
    writer.WriteStartElement( "book" );
    writer.WriteElementString( "title" , book.Title);
    writer.WriteElementString( "author" , book.Author.Name);
    writer.WriteElementString( "publisher" , book.Publisher);
    writer.WriteElementString( "price" , book.Price.ToString());
    writer.WriteEndElement();
    writer.Flush();
    }


output in books.xml is

<book>
.....
........
</book>



but I wanna output

<book key="A">
....
...
...
</book>



Just this. nothing else.

How to do this?

[edit]Code blocks added, HTML encoded - OriginalGriff[/edit]

解决方案

Well, like most computer programs it will only do what it is coded to do. If you want to add an attribute to an element then you need to add the code at the appropriate point. If you don't want the other elements in the file then don't write them. The documentation[^] shows all the appropriate method details.


Assuming you want to add an attribute to the book element use the XmlWriter.WriteAttributeString Method (String, String)[^].

So add to your code:

writer.WriteAttributeString( "key", "A" );


这篇关于写一个非常样本的Xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆