没有得到xml格式的字符串?

时间:2018-02-01 12:56:56

标签: c# xml

我正在尝试创建以下格式的xml文档:

<![CDATA[<Caption xmlns="http:happy.x.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.happybus.tv/yy/happybus.xsd">
 <TemplateID>xxxxx</TemplateID>
 <CaptionOptions>
   <CaptionField>
     <Field>xxx</Field>
     <Text>xxx</Text>
   </CaptionField>
   <CaptionField>
     <Field>xxxx</Field>
     <Text>""</Text>
   </CaptionField>
 </CaptionOptions>
 </Caption>]]>

这是我写的代码

XmlDocument xml2 = new XmlDocument();
XmlElement e = xml2.CreateElement("Caption");

e.InnerText ="Hello";
XmlElement template = xml2.CreateElement("TemplateID");
template.InnerText = "#TemplateID";

XmlElement captionOptions = xml2.CreateElement("CaptionOptions");
XmlElement captionField = xml2.CreateElement("CaptionField");

XmlElement fieldId = xml2.CreateElement("FieldID");
fieldId.InnerText = "#FieldID";
XmlElement textstring = xml2.CreateElement("TextString");
textstring.InnerText = "#TextString";    

captionField.AppendChild(fieldId);
captionField.AppendChild(textstring);    
captionOptions.AppendChild(captionField);

e.AppendChild(template);
e.AppendChild(captionOptions);    
xml2.AppendChild(e);    

StringWriter string_writer2 = new StringWriter();
XmlTextWriter xml_text_writer2 = new XmlTextWriter(string_writer2);
xml_text_writer2.Formatting = Formatting.Indented;
xml2.WriteTo(xml_text_writer2); // xml is your XmlDocument

string formattedXml2 = string_writer2.ToString();    
Console.Write(formattedXml2);

我尝试过使用不同XML文档的类似示例,但它显然有用,我甚至尝试过调试但是没有格式化。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用XDocument及相关课程?我发现他们使xml的手动构造更容易,更直观,因为代码看起来非常类似于xml。 ToString方法似乎以您希望的方式输出xml格式:

void Main()
{
    var xDoc = new XDocument
    (
        new XElement("Parent",
            new XElement("TemplateID", "xxxxx"),
            new XElement("CaptionOptions",
                new XElement("CaptionField",
                    new XElement("Field", "xxx"),
                    new XElement("Text", "xxx")
                ),
                new XElement("CaptionField",
                    new XElement("Field", "xxxx"),
                    new XElement("Text", "")
                )
            )
        )
    );

    Console.WriteLine(xDoc.ToString());

    //To enclose the xml in a CDATA, you could use:
    var cData = new XCData(xDoc.ToString());

    Console.WriteLine(cData.ToString());
}