Вызов printDocument(doc, System.out)
, где этот метод выглядит следующим образом:
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
(indent-amount
является необязательным и может не работать с вашей конкретной конфигурацией)
Я думаю, что это то, что вам нужно:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XNamespace ns = "http://www.acme.com/ABC";
DateTimeOffset date = new DateTimeOffset(2011, 9, 16, 10, 43, 54, 91,
TimeSpan.FromHours(1));
XDocument doc = new XDocument(
new XElement(ns + "ABC",
new XAttribute("xmlns", ns.NamespaceName),
new XAttribute(XNamespace.Xmlns + "xsi",
"http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute("fileName", "acmeth.xml"),
new XAttribute("date", date),
new XAttribute("origin", "TEST"),
new XAttribute("ref", "XX_88888")));
Console.WriteLine(doc);
}
}
Вы можете добавить объявления пространства имен в корневой элемент XmlDocument
следующим образом:
document.DocumentElement.SetAttribute("xmlns", "http://default-namespace");
document.DocumentElement.SetAttribute("xmlns:ns2", "http://other-namespace");
new XAttribute("xmlns", ns.NamespaceName)
? Вы уже устанавливаете пространство имен по умолчанию в строке выше, нет? – spender 30 September 2011 в 01:25