Skip to content

Instantly share code, notes, and snippets.

@BrennanBarker
Created November 8, 2023 03:22
Show Gist options
  • Select an option

  • Save BrennanBarker/8934077c1e1a81b81ecfaefd673728d3 to your computer and use it in GitHub Desktop.

Select an option

Save BrennanBarker/8934077c1e1a81b81ecfaefd673728d3 to your computer and use it in GitHub Desktop.
pydantic-xml example
from typing import Optional
from pydantic import AnyUrl
from pydantic_xml import BaseXmlModel, RootXmlModel, element
class Tags(RootXmlModel, tag="tags"): # type: ignore
root: list[str] = element(tag="tag")
class Notes(BaseXmlModel, tag="notes"):
message: str = element()
clss: str = element()
xml: Optional[str] = element(default=None)
block: Optional[str] = element(default=None)
class Bookmark(BaseXmlModel, tag="bookmark"):
link: AnyUrl = element()
tags: Optional[Tags] = None
notes: Optional[Notes] = None
class Bookmarks(BaseXmlModel, tag="bookmarks"):
bookmarks: list[Bookmark]
tags: Optional[Tags] = None
b1 = Bookmark(
link="http://google.com",
tags=Tags(["silver", "away"]),
notes=Notes(message="yo", clss="sup"),
)
b2 = Bookmark(link="http://ask-jeeves.com", notes=Notes(message="bruh", clss="dawg"))
bs = Bookmarks(bookmarks=[b1, b2], tags=Tags(["hi", "ho"]))
print(bs.to_xml(skip_empty=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment