本文整理汇总了C#中System.Xml.Linq.XDocument.Add方法的典型用法代码示例。如果您正苦于以下问题:C# XDocument.Add方法的具体用法?C# XDocument.Add怎么用?C# XDocument.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Xml.Linq.XDocument
的用法示例。
在下文中一共展示了XDocument.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Serialize
public XDocument Serialize(object obj)
{
var doc = new XDocument();
var t = obj.GetType();
var name = t.Name;
var options = t.GetAttribute<SerializeAsAttribute>();
if (options != null) {
name = options.TransformName(name);
}
var root = new XElement(name.AsNamespaced(Namespace));
Map(root, obj);
if (RootElement.HasValue()) {
var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root);
doc.Add(wrapper);
}
else {
doc.Add(root);
}
return doc;
}
示例2: OnXElement
public void OnXElement()
{
_runWithEvents = (bool)Params[0];
var numOfNodes = (int)Variation.Params[0];
var xml = (string)Variation.Params[1];
XElement e = XElement.Parse(xml);
if (Variation.Params.Length > 2)
{
var doc = new XDocument();
if ((bool)Variation.Params[2])
{
doc.Add(new XElement("{nsxx}X", e));
}
else
{
doc.Add(e);
}
}
// not connected nodes
TestReplacement(e, Data4XElem, numOfNodes);
// connected node mix
object[] copy = Data4XElem;
var eTemp = new XElement("cc", copy);
TestReplacement(e, copy, numOfNodes);
}
示例3: Main
static void Main(string[] args)
{
Console.Write("\n Create XML file using XDocument");
Console.Write("\n =================================\n");
XDocument xml = new XDocument();
xml.Declaration = new XDeclaration("1.0", "utf-8", "yes");
/*
* It is a quirk of the XDocument class that the XML declaration,
* a valid processing instruction element, cannot be added to the
* XDocument's element collection. Instead, it must be assigned
* to the document's Declaration property.
*/
XComment comment = new XComment("Demonstration XML");
xml.Add(comment);
XElement root = new XElement("root");
xml.Add(root);
XElement child1 = new XElement("child1", "child1 content");
XElement child2 = new XElement("child2");
XElement grandchild21 = new XElement("grandchild21", "content of grandchild21");
child2.Add(grandchild21);
root.Add(child1);
root.Add(child2);
Console.Write("\n{0}\n", xml.Declaration);
Console.Write(xml.ToString());
Console.Write("\n\n");
}
示例4: Generate
public XDocument Generate()
{
var mainDocument = new XDocument();
mainDocument.Add(GetDocumentType(_documentStandard));
mainDocument.Add(_htmlRoot.Generate());
return mainDocument;
}
示例5: ExportProjectToCofFile
public bool ExportProjectToCofFile(DTO_Project info, string exportDir)
{
// OVERVIEW ======================================
XElement rootElem = new XElement(BusinessLogic.Config.XML_KEY_COF_HEAD, info.Desc);
rootElem.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_ATTRIBUTE_PROJECT_NAME, info.ProjectName));
XDocument doc = new XDocument(rootElem);
// AUTHORS =======================================
XElement authorElem = new XElement(BusinessLogic.Config.XML_KEY_COF_GROUP);
authorElem.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_GROUP_ATTRIBUTE_NAME, info.GroupName));
foreach (DTO_Author author in info.Authors)
{
XElement authorDetail = new XElement(BusinessLogic.Config.XML_KEY_COF_AUTHOR);
authorDetail.Add(new XAttribute(BusinessLogic.Config.XML_KEY_COF_AUTHOR_ATTRIBUTE_NAME, author.Name));
authorDetail.Value = author.AdditionalInfo;
authorElem.Add(authorDetail);
}
// NOTES =========================================
XElement noteElem = new XElement(BusinessLogic.Config.XML_KEY_COF_NOTES);
foreach (string noteDetail in info.Notes)
{
noteElem.Add(new XElement(BusinessLogic.Config.XML_KEY_COF_NOTE_DETAIL, noteDetail));
}
// SOURCE EXPORT =================================
//TODO: copy project source to dir.
// EXPORT COF ====================================
doc.Add(authorElem);
doc.Add(noteElem);
return FileBusiness.XmlHandler.writeToFile(exportDir, doc, true);
}
示例6: btnGenerate_Click
private void btnGenerate_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection(String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",txtServer.Text,txtPort.Text,txtUser.Text,txtPassword.Text,txtDBName.Text));
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("select * from report", conn);
try
{
NpgsqlDataReader dr = command.ExecuteReader();
XDocument xmlTS = new XDocument();
// Données de base
xmlTS.Add(new XDocumentType("TS",null,null,null));
XElement ts = new XElement("TS",new XAttribute("version","2.0"));
xmlTS.Add(ts);
while (dr.Read())
{
XDocument xmlReport = XDocument.Parse(dr["report_source"].ToString());
XElement context = new XElement("context", new XElement("name",xmlReport.Element("report").Element("name").Value));
ts.Add(context);
foreach (XElement label in from i in xmlReport.Element("report").Descendants("label") select i)
{
XElement message = new XElement("message",
new XElement("source", label.Element("string").Value),
new XElement("translation",
new XAttribute("type", "unfinished"), "")
);
// if (chkWidth.Checked) message.AddFirst(new XElement("width", label.Element("rect").Element("width").Value));
context.Add(message);
}
}
xmlTS.Save(txtTSFilename.Text);
MessageBox.Show("Conversion terminée");
}
finally
{
conn.Close();
}
}
示例7: Test
public void Test()
{
//TODO: Make the parser add exception nodes when strings don't fully match
Decoder decode;
var masterDoc = new XDocument(new XElement("doc")).Root;
if (masterDoc == null) throw new Exception(".NET stopped working!");
decode = Decoder.FromPath("[*]");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Nodes()", decode.Local.ToString());
decode.Local.Compile();
decode = Decoder.FromPath("[*]{/note}");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Nodes()", decode.Local.ToString());
decode.Local.Compile();
Assert.AreEqual("a => a.Root.Nodes(\"note\")", decode.Data.ToString());
decode.Data.Compile();
decode = Decoder.FromPath("{/note}[entityRow]");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Nodes(\"entityRow\")", decode.Local.ToString());
decode.Local.Compile();
Assert.AreEqual("a => a.Root.Nodes(\"note\")", decode.Data.ToString());
decode.Data.Compile();
decode = Decoder.FromPath("{@descr}");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Attribute(\"descr\")", decode.Data.ToString());
decode.Data.Compile();
decode = Decoder.FromPath("{/dyn::rowSelector}");
masterDoc.Add(decode.Element);
//TODO: This is pretty sketchy. I should consider a different approach to handling namespaces.
//And how will I remember to update Decoder when I change the interfaces around?
//I need to get decode to build itself from hardcoded interface calls, so they'll break when I change the interface
// and not jus during testing
Assert.AreEqual("a => a.Root.Nodes(\"dyn\", \"rowSelector\")", decode.Data.ToString());
decode.Data.Compile();
decode = Decoder.FromPath("[:noteList/@rows]");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Root.NodeById(\"noteList\").Attribute(\"rows\")", decode.Local.ToString());
decode.Local.Compile();
decode = Decoder.FromPath("[@rows][1]");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.Attribute(\"rows\")", decode.Expressions.First().ToString());
Assert.AreEqual("a => a.ElementAtOrDefault(0)", decode.Expressions.Skip(1).First().ToString());
decode.Local.Compile();
decode = Decoder.FromPath("[../@rowSelector]{@body}");
masterDoc.Add(decode.Element);
Assert.AreEqual("a => a.get_Parent().Attribute(\"rowSelector\")", decode.Local.ToString());
decode.Local.Compile();
Assert.AreEqual("a => a.Attribute(\"body\")", decode.Data.ToString());
decode.Data.Compile();
}
示例8: PrestaSharpSerialize
/// <summary>
/// Serialize the object as XML
/// </summary>
/// <param name="obj">Object to serialize</param>
/// <returns>XML as string</returns>
public string PrestaSharpSerialize(object obj)
{
var doc = new XDocument();
var t = obj.GetType();
var name = t.Name;
var options = t.GetAttribute<SerializeAsAttribute>();
if (options != null)
{
name = options.TransformName(options.Name ?? name);
}
var root = new XElement(name.AsNamespaced(Namespace));
if (obj is IList)
{
var itemTypeName = "";
foreach (var item in (IList)obj)
{
var type = item.GetType();
var opts = type.GetAttribute<SerializeAsAttribute>();
if (opts != null)
{
itemTypeName = opts.TransformName(opts.Name ?? name);
}
if (itemTypeName == "")
{
itemTypeName = type.Name;
}
var instance = new XElement(itemTypeName);
Map(instance, item);
root.Add(instance);
}
}
else
Map(root, obj);
if (RootElement.HasValue())
{
var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root);
doc.Add(wrapper);
}
else
{
doc.Add(root);
}
return doc.ToString();
}
示例9: CreateXMLDocument
private void CreateXMLDocument()
{
XDocument document = new XDocument();
document.Declaration = new XDeclaration( "1.0", Encoding.UTF8.ToString(), "yes" );
document.Add( new XComment( "Current Inventory of AutoLot" ) );
XElement inventory = new XElement( "Inventory" );
inventory.Add( CarElement( "1", "Green", "BMW", "Stan" ) );
inventory.Add( CarElement( "2", "Pink", "Yugo", "Melvin" ) );
document.Add( inventory );
Console.WriteLine( document );
document.Save( "AutoLotInventory.xml" );
}
示例10: ExportXml
public static void ExportXml(string path, IEnumerable<SniffedPacket> packets) {
if (packets == null) {
throw new ArgumentNullException("packets");
}
XDocument xDoc = new XDocument(
new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty));
XElement xPackets = new XElement(
"Packets",
new XAttribute("Version", XmlVersion));
foreach (SniffedPacket packet in packets) {
XElement xPacket = new XElement("Packet");
xPacket.Add(new XAttribute("Elapsed", packet.ElapsedTime.TotalMilliseconds));
foreach (SniffedValue value in packet.Values) {
xPacket.Add(new XElement(value.Name, value.Value));
}
xPackets.Add(xPacket);
}
xDoc.Add(xPackets);
xDoc.Save(path);
}
示例11: Save
internal static void Save(QuoteList inQuoteList)
{
XDocument document = new XDocument();
document.Add(XElement.Parse(@"<QuoteList xmlns='http://kiander.com'></QuoteList>"));
document.Root.Add(new XAttribute("QuoteListId", inQuoteList.Id));
foreach (IQuote quote in inQuoteList.Quotes)
{
XElement quoteRecord = new XElement("QuoteRecord");
quoteRecord.Add(new XElement("QuoteID", quote.Id));
quoteRecord.Add(new XElement("Quote", quote.Text));
quoteRecord.Add(new XElement("Author", quote.Author));
XElement categories = new XElement("Categories");
if (quote.Categories != null)
{
foreach (string category in quote.Categories)
{
categories.Add(new XElement("Category", category));
}
}
if (quote.Categories == null || quote.Categories.Count < 1)
{
categories.Add(new XElement("Category", string.Empty));
}
quoteRecord.Add(categories);
document.Root.Add(quoteRecord);
}
if (File.Exists(DataFileHelper.FullPath(inQuoteList.Id)))
File.Delete(DataFileHelper.FullPath(inQuoteList.Id));
document.Save(DataFileHelper.FullPath(inQuoteList.Id));
}
示例12: GenerateXDoc
private static XDocument GenerateXDoc(IEnumerable<Project> projects)
{
XDocument xdoc = new XDocument();
var rootElement = new XElement("projects");
xdoc.Add(rootElement);
foreach (var project in projects)
{
rootElement.Add(
new XElement("project",
new XElement("name", project.Name),
new XElement("fundingSucceeded", project.FundingSucceeded),
new XElement("link", project.Link),
new XElement("currency", project.Currency),
new XElement("company", project.Company),
new XElement("fundingGoal", project.FundingGoal),
new XElement("backers", project.Backers),
new XElement("totalFunding", project.TotalFunding),
new XElement("description", project.Description),
new XElement("startDate", project.StartDate),
new XElement("endDate", project.EndDate),
new XElement("category", project.Category),
new XElement("levels", project.Levels.Select(
x => new XElement("level",
new XElement("backers", x.Backers),
new XElement("maxBackersAllowed", x.MaxBackersAllowed),
new XElement("remainingBackersAllowed", x.RemainingBackersAllowed),
new XElement("isSoldOut", x.IsSoldOut),
new XElement("description", x.Description),
new XElement("totalFunding", x.TotalFunding),
new XElement("money", x.Money),
new XElement("moneyUSD", x.MoneyUSD))))));
}
return xdoc;
}
示例13: CreatePayload
private XDocument CreatePayload(String roleName, String packageUrl, String pathToConfigurationFile, String label)
{
String configurationFile = File.ReadAllText(pathToConfigurationFile);
String base64ConfigurationFile = ConvertToBase64String(configurationFile);
String base64Label = ConvertToBase64String(label);
XElement xMode = new XElement(wa + "Mode", "auto");
XElement xPackageUrl = new XElement(wa + "PackageUrl", packageUrl);
XElement xConfiguration = new XElement(wa + "Configuration", base64ConfigurationFile);
XElement xLabel = new XElement(wa + "Label", base64Label);
XElement xRoleToUpgrade = new XElement(wa + "RoleToUpgrade", roleName);
XElement upgradeDeployment = new XElement(wa + "UpgradeDeployment");
upgradeDeployment.Add(xMode);
upgradeDeployment.Add(xPackageUrl);
upgradeDeployment.Add(xConfiguration);
upgradeDeployment.Add(xLabel);
upgradeDeployment.Add(xRoleToUpgrade);
XDocument payload = new XDocument();
payload.Add(upgradeDeployment);
payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
return payload;
}
示例14: Main
static void Main(string[] args)
{
var context = new GeographyEntities();
var countriesQuery = context.Countries
.Where(c => c.Monasteries.Any())
.OrderBy(c => c.CountryName)
.Select(c => new
{
countryName = c.CountryName,
monasteries = c.Monasteries
.OrderBy(m => m.Name)
.Select(m => m.Name)
});
var xmlDoc = new XDocument();
var xmlRoot = new XElement("monasteries");
xmlDoc.Add(xmlRoot);
foreach (var country in countriesQuery)
{
var countryXml = new XElement("country", new XAttribute("name", country.countryName));
xmlRoot.Add(countryXml);
foreach (var monastery in country.monasteries)
{
var monasteryXml = new XElement("monastery", monastery);
countryXml.Add(monasteryXml);
}
}
Console.WriteLine(xmlDoc);
xmlDoc.Save("monasteries.xml");
}
示例15: Submit
public void Submit(Order order, XDocument document)
{
if (order == null)
{
throw new ArgumentNullException("order");
}
if (document == null)
{
throw new ArgumentNullException("document");
}
var ordersElement = document.Element("Orders");
if (ordersElement == null)
{
ordersElement = new XElement("Orders");
document.Add(ordersElement);
}
var orderElement = new XElement("Order",
new XAttribute("OrderType", order.OrderType),
new XAttribute("Shares", order.Shares),
new XAttribute("StopLimitPrice", order.StopLimitPrice),
new XAttribute("TickerSymbol", order.TickerSymbol),
new XAttribute("TimeInForce", order.TimeInForce),
new XAttribute("TransactionType", order.TransactionType),
new XAttribute("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture))
);
ordersElement.Add(orderElement);
string message = String.Format(CultureInfo.CurrentCulture, Resources.LogOrderSubmitted,
orderElement.ToString());
logger.Log(message, Category.Debug, Priority.Low);
}