开发者

Add a Text line in xml on a particular location?

How can I insert the following stylesheet information into my existing xml file which is created using C#?

<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>

Or.... Can I add this line at the time of creation of the new XML file?

Edit:

I tried to achieve the above using XmlSerialier (hit and trial), something like this:

// assumes 'XML' file exists.
XmlDocument doc = new XmlDocument();
XElement dataElements = XElement.Load("_fileName.xml");
XmlSerializer xs = new XmlSerializer(typeof(Parents));
var ms = new MemoryStream();
xs.Serialize(ms, parents);
ms.Seek(0, SeekOrigin.Begin); // rewind stream to beginning
doc.Load(ms);
XmlProcessingInstruction pi;
string data = "type=\"text/xsl\" href=\"_fileName.xsl\"";
pi = doc.CreateProcessingInstruction("xml-stylesheet", data);
doc.InsertBefore(pi, doc.DocumentElement); // insert before root
doc.DocumentElement.Attributes.RemoveAll(); // remove namespaces

But the output xml is getting corrupted:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>
<parents />

Whereas the desired output is something like:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>
<pa开发者_StackOverflow中文版rents>
<parent>
<Child1>
<child2>
</parent>
</parents>

Did this help to understand what's my problem???


You didn't answer the question.. "what lib do you use".

Although I advise:

XDocument

if you would use it you could do something like:

XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

document.Add(new XProcessingInstruction(
      "xml-stylesheet", "type=\"text/xsl\" href=\"_fileName.xsl\""));
//and then your actual document...
document.Add(
    new XElement("parent",
         new XElement("child1"),
         new XElement("child2")
    )
);

EDIT:

Ok So you could do it like:

 XDocument document = XDocument.Load("file");
 document.AddFirst(new XProcessingInstruction(
    "xml-stylesheet", "type=\"text/xsl\" href=\"LogStyle.xsl\""));

Is this what you're looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜